Part I: Data Merging and Cleaning¶

In [1]:
# ============================================================================
# Pre-processing & Data Addition - Manually Enter Brunei Electricity Cost
# ============================================================================
import os
import pandas as pd

# Locate the raw CSV
current_dir = os.getcwd()
project_root = os.path.dirname(current_dir)
data_folder = os.path.join(project_root, 'Data')
file_path_raw = os.path.join(data_folder, 'Input-Cost of Electricity by Country.csv')

if os.path.exists(file_path_raw):
    df_elec = pd.read_csv(file_path_raw)
    
    # Check if BRN exists in the dataset
    if 'BRN' in df_elec['ISO3'].values:
        # If it exists, overwrite the 2023 value
        df_elec.loc[df_elec['ISO3'] == 'BRN', '2023'] = 0.06
        print("Brunei (BRN) found in the dataset. Electricity cost updated to 0.06.")
    else:
        # If it does NOT exist, append a new row for BRN
        # Create a new row with NaN for other columns
        new_row = pd.DataFrame({
            'country / region': ['Brunei Darussalam'],
            'ISO3': ['BRN'],
            '2023': [0.06]
        })
        # Add other columns (like 2024, 2025) with NaN if they exist
        for col in df_elec.columns:
            if col not in new_row.columns:
                new_row[col] = pd.NA
                
        # Concatenate and reorder to match original columns
        df_elec = pd.concat([df_elec, new_row], ignore_index=True)
        df_elec = df_elec[df_elec.columns.drop('2023').tolist() + ['2023']]
        print("Brunei (BRN) was missing. Successfully added with a 2023 value of 0.06.")
        
    # Save back to the original file
    df_elec.to_csv(file_path_raw, index=False)
else:
    print(f"Warning: File not found at {file_path_raw}")
Brunei (BRN) found in the dataset. Electricity cost updated to 0.06.
In [2]:
import os
import pandas as pd

# ============================================================================
# 1. Set up paths
# ============================================================================
current_dir = os.getcwd()
project_root = os.path.dirname(current_dir)
data_folder = os.path.join(project_root, 'Data')

file_path_raw = os.path.join(data_folder, 'Input-Building-green-dataset-final-05-13-2024.xlsx')

if not os.path.exists(file_path_raw):
    raise FileNotFoundError(f"File not found at {file_path_raw}. Please check the filename and Data folder.")

# ============================================================================
# 2. Read the specific sheet: "Final dataset"
# ============================================================================
print("Loading 'Final dataset' sheet...")
df_raw_full = pd.read_excel(file_path_raw, sheet_name="Final dataset")

print(f"Original shape of 'Final dataset': {df_raw_full.shape}")

# ============================================================================
# 3. Extract columns A, B, AN, and CI to CO
# ============================================================================
# A=0, B=1, AN=39, CI-CO = 86 to 92
cols_to_keep = [0, 1, 39] + list(range(86, 93))

if df_raw_full.shape[1] > 92:
    df_raw = df_raw_full.iloc[:, cols_to_keep].copy()
    print(f"\nSuccessfully extracted columns. New shape: {df_raw.shape}")
else:
    print("\n⚠️ Warning: The dataset has fewer columns than expected. Please check the raw file.")
    print(f"Total columns available: {df_raw_full.shape[1]}")
    df_raw = df_raw_full 

print("\n--- Extracted Columns ---")
print(df_raw.columns.tolist())

print("\n--- Preview of extracted data ---")
display(df_raw.head(3))
Loading 'Final dataset' sheet...
Original shape of 'Final dataset': (88, 153)

Successfully extracted columns. New shape: (88, 10)

--- Extracted Columns ---
['DEM-INFO-01', 'DEM-INFO-02', 'ENF-PERM-03', 'REQ-PAS-02', 'REQ-PAS-03', 'REQ-PAS-04', 'REQ-PAS-05', 'REQ-PAS-06', 'REQ-PAS-07', 'REQ-PAS-08']

--- Preview of extracted data ---
DEM-INFO-01 DEM-INFO-02 ENF-PERM-03 REQ-PAS-02 REQ-PAS-03 REQ-PAS-04 REQ-PAS-05 REQ-PAS-06 REQ-PAS-07 REQ-PAS-08
0 Albania ALB Yes 3 Yes Yes Yes .. .. ..
1 Algeria DZA .. .. .. .. .. .. .. ..
2 Argentina ARG Yes 4 Yes Yes Yes No .. Yes
In [3]:
from functools import reduce

# ============================================================================
# 1. Set up paths
# ============================================================================
current_dir = os.getcwd()
project_root = os.path.dirname(current_dir)
data_folder = os.path.join(project_root, 'Data')
output_folder = os.path.join(project_root, 'Output')
os.makedirs(output_folder, exist_ok=True)

# ============================================================================
# 2. Load and clean main dataset (df_raw)
# ============================================================================
file_path_raw = os.path.join(data_folder, 'Input-Building-green-dataset-final-05-13-2024.xlsx')
df_raw_full = pd.read_excel(file_path_raw, sheet_name="Final dataset")

# Keep columns A(0), B(1), AN(39), and CI(86) to CO(92)
cols_to_keep = [0, 1, 39] + list(range(86, 93))
df_raw = df_raw_full.iloc[:, cols_to_keep].copy()

# Rename the first two columns
cols = df_raw.columns.tolist()
cols[0] = 'country'
cols[1] = 'ISO3'
df_raw.columns = cols

# Clean ISO3 and drop rows where ISO3 is missing
df_raw = df_raw.dropna(subset=['ISO3'])
df_raw['ISO3'] = df_raw['ISO3'].astype(str).str.strip().str.upper()

# ============================================================================
# 3. Load and clean external Xi datasets
# ============================================================================

# 3.1 Corruption Perceptions Index
df_cpi = pd.read_csv(os.path.join(data_folder, 'Input-Corruption_Perceptions_Index 2023.csv'))
df_cpi = df_cpi[['ISO3', 'CPI 2023 Score']].copy()
df_cpi = df_cpi.rename(columns={'CPI 2023 Score': 'Corruption_Perceptions_Index'})
df_cpi['ISO3'] = df_cpi['ISO3'].astype(str).str.strip().str.upper()

# 3.2 Cost of Electricity
df_elec = pd.read_csv(os.path.join(data_folder, 'Input-Cost of Electricity by Country.csv'))
df_elec = df_elec[['ISO3', '2023']].copy()
df_elec = df_elec.rename(columns={'2023': 'Cost_of_Electricity_USD/KWH'})
df_elec['ISO3'] = df_elec['ISO3'].astype(str).str.strip().str.upper()

# 3.3 GDP Per Capita (Header on row 5)
df_gdp = pd.read_csv(os.path.join(data_folder, 'Input-GDP_Per_Capita_Data.csv'), header=4)
df_gdp = df_gdp.iloc[:, [1, 67]].copy()
df_gdp.columns = ['ISO3', 'GDP_Per_Capita']
df_gdp['ISO3'] = df_gdp['ISO3'].astype(str).str.strip().str.upper()

# 3.4 Global Adaption (ND-GAIN)
df_ndgain = pd.read_csv(os.path.join(data_folder, 'Input-Global_Adaption_2023.csv'))
df_ndgain = df_ndgain[['ISO3', 'ND-GAIN Score']].copy()
df_ndgain = df_ndgain.rename(columns={'ND-GAIN Score': 'Climate_Change_Global_Adoption'})
df_ndgain['ISO3'] = df_ndgain['ISO3'].astype(str).str.strip().str.upper()

# 3.5 Government Effectiveness (Header on row 5)
df_gov = pd.read_csv(os.path.join(data_folder, 'Input-Government_Effectiveness.csv'), header=4)
df_gov = df_gov.iloc[:, [1, 67]].copy()
df_gov.columns = ['ISO3', 'Government_Effectiveness']
df_gov['ISO3'] = df_gov['ISO3'].astype(str).str.strip().str.upper()

# 3.6 Urban Population Rate (Header on row 5)
df_urban = pd.read_csv(os.path.join(data_folder, 'Input-Urban_Population_Rate_Data.csv'), header=4)
df_urban = df_urban.iloc[:, [1, 67]].copy()
df_urban.columns = ['ISO3', 'Urban_Population_Rate']
df_urban['ISO3'] = df_urban['ISO3'].astype(str).str.strip().str.upper()


# ============================================================================
# 4. Merge datasets (Left join based on ISO3)
# ============================================================================
print("Merging datasets...")
dfs_to_merge = [df_raw, df_cpi, df_elec, df_gdp, df_ndgain, df_gov, df_urban]
df_merged_all = reduce(lambda left, right: pd.merge(left, right, on='ISO3', how='left'), dfs_to_merge)

# Round electricity price to 2 decimals
df_merged_all['Cost_of_Electricity_USD/KWH'] = df_merged_all['Cost_of_Electricity_USD/KWH'].round(2)

print(f"Merged dataset shape: {df_merged_all.shape}")
display(df_merged_all.head(3))
In [4]:
# ============================================================================
# 5. Rename columns and reorder to match the final format
# ============================================================================

print("Renaming and reordering columns...")

# Define the mapping dictionary
rename_dict = {
    'country': 'Countries/Economies',
    'ISO3': 'Country Code',
    'ENF-PERM-03': 'Passive_Design Compliance',
    'Urban_Population_Rate': 'Urban_Population_Rate_Data_2023',
    'GDP_Per_Capita': 'GDP_Per_Capita_Data_2023',
    'Government_Effectiveness': 'Government_Effectiveness_2023',
    'Cost_of_Electricity_USD/KWH': 'Cost_of_Electricity_2023_USD/KWH',
    'Corruption_Perceptions_Index': 'Corruption_Perceptions_Index_2023',
    'Climate_Change_Global_Adoption': 'Global_Adaption_Index_2023',
    'REQ-PAS-02': 'Passive_Design_Enforcement_Mechanisms_Checklist',
    'REQ-PAS-03': 'Passive Design Enforcement Mechanisms: Checklist of Passive Design',
    'REQ-PAS-04': 'Passive Design Enforcement Mechanisms: Thermal Transmittance or Insulation Calculations for Building Envelope',
    'REQ-PAS-05': 'Passive Design Enforcement Mechanisms: Solar Heat Gains Calculations for Building Envelope',
    'REQ-PAS-06': 'Passive Design Enforcement Mechanisms: Glazing Factors for Fenestration',
    'REQ-PAS-07': 'Passive Design Enforcement Mechanisms: Permanent Shading',
    'REQ-PAS-08': 'Passive Design Enforcement Mechanisms: Air Barrier, Air Leakage, or Air Infiltration'
}

# Apply the renaming
df_final = df_merged_all.rename(columns=rename_dict)

# Define the exact order of columns based on your request
desired_order = [
    'Countries/Economies',
    'Country Code',
    'Passive_Design Compliance',
    'Urban_Population_Rate_Data_2023',
    'GDP_Per_Capita_Data_2023',
    'Government_Effectiveness_2023',
    'Cost_of_Electricity_2023_USD/KWH',
    'Corruption_Perceptions_Index_2023',
    'Global_Adaption_Index_2023',
    'Passive_Design_Enforcement_Mechanisms_Checklist',
    'Passive Design Enforcement Mechanisms: Checklist of Passive Design',
    'Passive Design Enforcement Mechanisms: Thermal Transmittance or Insulation Calculations for Building Envelope',
    'Passive Design Enforcement Mechanisms: Solar Heat Gains Calculations for Building Envelope',
    'Passive Design Enforcement Mechanisms: Glazing Factors for Fenestration',
    'Passive Design Enforcement Mechanisms: Permanent Shading',
    'Passive Design Enforcement Mechanisms: Air Barrier, Air Leakage, or Air Infiltration'
]

# Reorder columns
df_final = df_final[desired_order]

print(f"Final dataframe shape: {df_final.shape}")
print("\n--- Final Columns ---")
print(df_final.columns.tolist())
print("\n--- Preview of the final data ---")
display(df_final.head(3))

# ============================================================================
# 6. Save the final full dataset
# ============================================================================
final_output_path = os.path.join(output_folder, 'Merged_All_Countries_Final.csv')
df_final.to_csv(final_output_path, index=False)
print(f"\nFull merged and formatted dataset saved to: {final_output_path}")
In [5]:
import numpy as np

# ============================================================================
# 7. Clean data and restrict to the 54 countries
# ============================================================================
print("Cleaning data and filtering to final sample...")

# Create a copy for filtering so we don't alter the full 88-country df yet
df_54 = df_final.copy()

# 1. Replace '..' with actual NaN values across the whole dataframe
df_54 = df_54.replace('..', np.nan)

# 2. Convert the specific column to numeric (forces non-numeric values to NaN)
target_col = 'Passive_Design_Enforcement_Mechanisms_Checklist'
df_54[target_col] = pd.to_numeric(df_54[target_col], errors='coerce')

# 3. Identify dropped countries and the reason
# A country is dropped if target_col is NaN OR if any of the 6 X variables are NaN
x_vars = [
    'Urban_Population_Rate_Data_2023', 
    'GDP_Per_Capita_Data_2023', 
    'Government_Effectiveness_2023', 
    'Cost_of_Electricity_2023_USD/KWH',
    'Corruption_Perceptions_Index_2023', 
    'Global_Adaption_Index_2023'
]

dropped_reasons = []
kept_indices = []

for idx, row in df_54.iterrows():
    missing_vars = []
    
    # Check if the target (Y) is missing
    if pd.isna(row[target_col]):
        missing_vars.append('Passive_Design_Enforcement_Mechanisms_Checklist')
        
    # Check X variables
    for var in x_vars:
        if pd.isna(row[var]):
            missing_vars.append(var)
            
    if len(missing_vars) > 0:
        dropped_reasons.append({
            'Country': row['Countries/Economies'],
            'Country Code': row['Country Code'],
            'Reason': ', '.join(missing_vars)
        })
    else:
        kept_indices.append(idx)

# Create dataframe of dropped countries for the README
df_excluded = pd.DataFrame(dropped_reasons)

# Subset the final 54 countries
df_54 = df_54.loc[kept_indices].reset_index(drop=True)

print(f"\nOriginal number of countries: {len(df_final)}")
print(f"Final number of countries: {len(df_54)}")
print(f"Number of excluded countries: {len(df_excluded)}")


# ============================================================================
# 8. Check missing values for the 6 mechanisms across the 54 countries
# ============================================================================
print("\n--- Missing values in the 6 mechanism variables (among 54 countries) ---")

mech_vars = [
    'Passive Design Enforcement Mechanisms: Checklist of Passive Design',
    'Passive Design Enforcement Mechanisms: Thermal Transmittance or Insulation Calculations for Building Envelope',
    'Passive Design Enforcement Mechanisms: Solar Heat Gains Calculations for Building Envelope',
    'Passive Design Enforcement Mechanisms: Glazing Factors for Fenestration',
    'Passive Design Enforcement Mechanisms: Permanent Shading',
    'Passive Design Enforcement Mechanisms: Air Barrier, Air Leakage, or Air Infiltration'
]

# Count missing values per mechanism
print(df_54[mech_vars].isna().sum())

# Find which specific countries have missing values in any of the 6 mechanisms
missing_mech_countries = df_54[df_54[mech_vars].isna().any(axis=1)]
print("\nCountries with missing values in any of the 6 mechanisms:")
display(missing_mech_countries[['Countries/Economies'] + mech_vars])


# ============================================================================
# 9. Save outputs
# ============================================================================
# Save the 54-country clean dataset
final_54_path = os.path.join(output_folder, 'Final_54_Countries.csv')
df_54.to_csv(final_54_path, index=False)
print(f"\nFinal 54-country dataset saved to: {final_54_path}")

# Save the excluded countries list
excluded_path = os.path.join(output_folder, 'Excluded_Countries_List.csv')
df_excluded.to_csv(excluded_path, index=False)
print(f"Excluded countries list saved to: {excluded_path}")
Cleaning data and filtering to final sample...

Original number of countries: 88
Final number of countries: 54
Number of excluded countries: 34

--- Missing values in the 6 mechanism variables (among 54 countries) ---
Passive Design Enforcement Mechanisms: Checklist of Passive Design                                                7
Passive Design Enforcement Mechanisms: Thermal Transmittance or Insulation Calculations for Building Envelope     4
Passive Design Enforcement Mechanisms: Solar Heat Gains Calculations for Building Envelope                        7
Passive Design Enforcement Mechanisms: Glazing Factors for Fenestration                                           8
Passive Design Enforcement Mechanisms: Permanent Shading                                                         10
Passive Design Enforcement Mechanisms: Air Barrier, Air Leakage, or Air Infiltration                              8
dtype: int64

Countries with missing values in any of the 6 mechanisms:
Countries/Economies Passive Design Enforcement Mechanisms: Checklist of Passive Design Passive Design Enforcement Mechanisms: Thermal Transmittance or Insulation Calculations for Building Envelope Passive Design Enforcement Mechanisms: Solar Heat Gains Calculations for Building Envelope Passive Design Enforcement Mechanisms: Glazing Factors for Fenestration Passive Design Enforcement Mechanisms: Permanent Shading Passive Design Enforcement Mechanisms: Air Barrier, Air Leakage, or Air Infiltration
0 Albania Yes Yes Yes NaN NaN NaN
1 Argentina Yes Yes Yes No NaN Yes
8 Bulgaria Yes Yes Yes Yes NaN NaN
10 Colombia NaN Yes Yes Yes Yes Yes
12 Czechia NaN Yes Yes Yes Yes Yes
13 Finland No Yes Yes Yes NaN Yes
17 Greece NaN Yes NaN NaN Yes No
24 Kenya NaN No No No No No
31 Malaysia No NaN NaN NaN NaN NaN
32 Mexico Yes Yes, but inconsistently Yes, but inconsistently NaN No No
38 Pakistan Yes, but inconsistently NaN NaN NaN NaN NaN
41 Qatar NaN NaN NaN NaN NaN NaN
46 Spain NaN Yes NaN Yes Yes Yes, but inconsistently
50 United Kingdom Yes Yes Yes Yes NaN NaN
51 United States NaN Yes NaN NaN NaN NaN
52 Uruguay Yes NaN NaN NaN NaN NaN
Final 54-country dataset saved to: your/path/to/reproducibility package/Output/Final_54_Countries.csv
Excluded countries list saved to: your/path/to/reproducibility package/Output/Excluded_Countries_List.csv
In [6]:
# Get current directory (where this notebook is located, i.e., inside ./Code/)
current_dir = os.getcwd()

# Go up one level to the project root (WB Reproducibility Package/)
project_root = os.path.dirname(current_dir)

# Define output folder path where the cleaned data was saved
output_folder = os.path.join(project_root, 'Output')

# Construct full path to the newly generated 54-country CSV file
file_path = os.path.join(output_folder, 'Final_54_Countries.csv')

# Check if file exists
if not os.path.exists(file_path):
    raise FileNotFoundError(
        f"File not found at {file_path}. Please ensure you have run the data merging and cleaning script first."
    )

# Read the cleaned 54-country dataset into a DataFrame
journal_dataset_cleaned = pd.read_csv(file_path)

# ============================================================================
# Map the long descriptive column names back to the short names used in models
# ============================================================================
rename_back_dict = {
    'Passive_Design_Enforcement_Mechanisms_Checklist': 'Passive_Design_Checklist_Number',
    'Cost_of_Electricity_2023_USD/KWH': 'Cost_of_Electricity_USD/KWH',
    'GDP_Per_Capita_Data_2023': 'GDP_Per_Capita',
    'Urban_Population_Rate_Data_2023': 'Urban_Population_Rate',
    'Government_Effectiveness_2023': 'Government_Effectiveness',
    'Corruption_Perceptions_Index_2023': 'Corruption_Perceptions_Index',
    'Global_Adaption_Index_2023': 'Climate_Change_Global_Adoption',
    
    # Mechanism variables (used in the Logit models)
    'Passive Design Enforcement Mechanisms: Glazing Factors for Fenestration': 
        'Glazing Factors for Fenestration',
    'Passive Design Enforcement Mechanisms: Thermal Transmittance or Insulation Calculations for Building Envelope': 
        'Thermal Transmittance or Insulation Calculations for Building Envelope',
    'Passive Design Enforcement Mechanisms: Solar Heat Gains Calculations for Building Envelope': 
        'Solar Heat Gains Calculations for Building Envelope',
    'Passive Design Enforcement Mechanisms: Checklist of Passive Design': 
        'Checklist of Passive Design',
    'Passive Design Enforcement Mechanisms: Permanent Shading': 
        'Permanent Shading',
    'Passive Design Enforcement Mechanisms: Air Barrier, Air Leakage, or Air Infiltration': 
        'Air Barrier, Air Leakage, or Air Infiltration'
}

# Rename columns back to match the analysis code
journal_dataset_cleaned = journal_dataset_cleaned.rename(columns=rename_back_dict)

# Quick check
print(f"Loaded {len(journal_dataset_cleaned)} countries for analysis.")
display(journal_dataset_cleaned.head(2))
In [7]:
# Get current directory (where this notebook is located, i.e., inside ./Code/)
current_dir = os.getcwd()

# Go up one level to the project root (WB Reproducibility Package/)
project_root = os.path.dirname(current_dir)

# Define output folder path (since the merged file is saved in the Output folder)
output_folder = os.path.join(project_root, 'Output')

# Construct full path to the newly generated 54-country CSV file
file_path = os.path.join(output_folder, 'Final_54_Countries.csv')

# Optional: check if file exists, otherwise print helpful message
if not os.path.exists(file_path):
    raise FileNotFoundError(
        f"File not found at {file_path}. Please ensure you have run the data cleaning script "
        f"and 'Final_54_Countries.csv' is placed in the 'Output' folder."
    )

# Read the file into a DataFrame
journal_dataset3 = pd.read_csv(file_path)

Part 2: Descriptive Statistics (Figures 1 & 2)¶

This section plots the histograms of all numerical variables and saves the combined output as Fig 1&2.png.

In [8]:
# Data Visualization before Modelling
import matplotlib.pyplot as plt

# Ensure output folder exists (reuse project_root from previous cell)
current_dir = os.getcwd()
project_root = os.path.dirname(current_dir)
output_folder = os.path.join(project_root, 'Output')
os.makedirs(output_folder, exist_ok=True)

# Select numerical columns and plot histograms
num_cols = journal_dataset3.select_dtypes(include=['number']).columns
journal_dataset3[num_cols].hist(bins=20, figsize=(15, 10))
plt.suptitle("Histograms of Numerical Variables", fontsize=14)

# Save the figure as "Fig 1&2.png" (matches your paper's Figure 1 and 2)
plt.savefig(os.path.join(output_folder, 'Fig 1&2.png'),
            dpi=300, bbox_inches='tight')

plt.show()
No description has been provided for this image

Part 3: Variable Construction and Final Data Preparation¶

This section converts the Passive_Design Compliance variable into a binary indicator (where "yes" = 1, otherwise 0) and selects the final set of variables used in the regression models.

In [9]:
# Rename the Dataset & Data Cleaning

journal_dataset3["Passive_Design Compliance"] = (
    journal_dataset3["Passive_Design Compliance"]
    .str.strip()
    .str.lower()
)

journal_dataset3["Passive_Design_Compliance_Binary"] = journal_dataset3["Passive_Design Compliance"].apply(
    lambda x: 1 if isinstance(x, str) and ("yes" in x) else 0
)

journal_dataset_cleaned = journal_dataset3.rename(columns={
    "Countries/Economies": "Country",
    "Country Code": "ISO3",
    "Passive_Design Compliance": "Passive_Design_Compliance_Original",
    "Urban_Population_Rate_Data_2023": "Urban_Population_Rate",
    "GDP_Per_Capita_Data_2023": "GDP_Per_Capita",
    "Government_Effectiveness_2023": "Government_Effectiveness",
    "Cost_of_Electricity_2023_USD/KWH": "Cost_of_Electricity_USD/KWH",
    "Corruption_Perceptions_Index_2023":"Corruption_Perceptions_Index",
    "Global_Adaption_Index_2023":"Climate_Change_Global_Adoption",
    "Passive_Design_Enforcement_Mechanisms_Checklist":"Passive_Design_Checklist_Number"
})[ 
    ["Country", "ISO3", "Passive_Design_Compliance_Binary",
     "Urban_Population_Rate", "GDP_Per_Capita", "Government_Effectiveness",
     "Cost_of_Electricity_USD/KWH", "Corruption_Perceptions_Index", "Climate_Change_Global_Adoption",
     "Passive_Design_Checklist_Number"]
]

Part 4: Full Ordered Logit Regression Model (Table 5)¶

This section estimates the baseline Ordered Logit Model including all six X variables. It formats the regression output into a standard journal table and saves it as Table_5.csv.

In [10]:
# First Ordered Logit Regression with all X Variables

import statsmodels.api as sm
from statsmodels.miscmodels.ordinal_model import OrderedModel
import pandas as pd
import numpy as np
import os

# Ensure output folder exists
current_dir = os.getcwd()
project_root = os.path.dirname(current_dir)
output_folder = os.path.join(project_root, 'Output')
os.makedirs(output_folder, exist_ok=True)

# Ordered Logit Model
Y = journal_dataset_cleaned["Passive_Design_Checklist_Number"]
X = journal_dataset_cleaned[["Urban_Population_Rate", "GDP_Per_Capita", 
                             "Government_Effectiveness", "Cost_of_Electricity_USD/KWH",
                             "Corruption_Perceptions_Index", "Climate_Change_Global_Adoption"]]

ordered_model = OrderedModel(Y, X, distr='logit')
ordered_result = ordered_model.fit(method='bfgs', disp=False)

# Print standard summary (for interactive checking)
print("="*60)
print("STANDARD STATSMODELS SUMMARY")
print("="*60)
print(ordered_result.summary())

# ============================================================================
# Format output as standard journal table
# ============================================================================

# Dictionary mapping raw variable names to journal display names
label_map = {
    "Urban_Population_Rate": "Urban population rate",
    "GDP_Per_Capita": "GDP per capita (US$)",
    "Government_Effectiveness": "Government effectiveness",
    "Cost_of_Electricity_USD/KWH": "Electricity cost (USD/kWh)",
    "Corruption_Perceptions_Index": "Corruption Perceptions Index",
    "Climate_Change_Global_Adoption": "Climate adaptation index (ND-GAIN)"
}

# Helper function to format numbers (handles small decimals like 0.0000161)
def format_val(val):
    if val == 0:
        return "0.000"
    # Use 7 decimal places and strip trailing zeros to match journal format
    formatted = f"{val:.7f}".rstrip('0')
    if formatted.endswith('.'):
        formatted += '0'
    return formatted

# Extract model fit statistics
nobs = int(ordered_result.nobs)
llf = ordered_result.llf
aic = ordered_result.aic
bic = ordered_result.bic

# Build the formatted table data
journal_data = []
journal_data.append(["", "Enforcement level (0–6)"])

for var in X.columns:
    label = label_map.get(var, var)
    coef = ordered_result.params[var]
    se = ordered_result.bse[var]
    
    coef_str = format_val(coef)
    se_str = f"({format_val(se)})"
    
    journal_data.append([label, coef_str])
    journal_data.append(["", se_str])

journal_data.append(["Observations", str(nobs)])
journal_data.append(["Log-likelihood", f"{llf:.2f}"])
journal_data.append(["AIC", f"{aic:.1f}"])
journal_data.append(["BIC", f"{bic:.1f}"])

# Create DataFrame for the journal format
df_journal = pd.DataFrame(journal_data, columns=["Variable", "Model"])

# Print the journal format to console
print("\n" + "="*60)
print("JOURNAL FORMAT OUTPUT")
print("="*60)
for row in journal_data:
    print(f"{row[0]}\t{row[1]}")

# Save ONLY the journal format as CSV
table5_path = os.path.join(output_folder, 'Table_5_Appendix_A.csv')
df_journal.to_csv(table5_path, index=False)

print(f"\nTable 5 (Journal Format) saved to: {table5_path}")
============================================================
STANDARD STATSMODELS SUMMARY
============================================================
                                    OrderedModel Results                                   
===========================================================================================
Dep. Variable:     Passive_Design_Checklist_Number   Log-Likelihood:                -98.296
Model:                                OrderedModel   AIC:                             220.6
Method:                         Maximum Likelihood   BIC:                             244.5
Date:                             Tue, 24 Nov 2026                                         
Time:                                     13:08:38                                         
No. Observations:                               54                                         
Df Residuals:                                   42                                         
Df Model:                                       12                                         
==================================================================================================
                                     coef    std err          z      P>|z|      [0.025      0.975]
--------------------------------------------------------------------------------------------------
Urban_Population_Rate              0.0046      0.018      0.259      0.795      -0.030       0.040
GDP_Per_Capita                  1.681e-05   1.72e-05      0.975      0.329    -1.7e-05    5.06e-05
Government_Effectiveness           0.5562      0.862      0.646      0.519      -1.132       2.245
Cost_of_Electricity_USD/KWH        3.5815      2.540      1.410      0.159      -1.397       8.560
Corruption_Perceptions_Index      -0.0268      0.044     -0.610      0.542      -0.113       0.059
Climate_Change_Global_Adoption     0.0022      0.061      0.036      0.971      -0.118       0.122
0.0/1.0                           -1.6145      2.586     -0.624      0.532      -6.682       3.453
1.0/2.0                           -0.3328      0.429     -0.776      0.438      -1.174       0.508
2.0/3.0                           -0.4174      0.388     -1.076      0.282      -1.178       0.343
3.0/4.0                           -0.2836      0.333     -0.852      0.394      -0.936       0.369
4.0/5.0                           -0.2060      0.312     -0.661      0.509      -0.817       0.405
5.0/6.0                            0.0990      0.298      0.333      0.739      -0.484       0.682
==================================================================================================

============================================================
JOURNAL FORMAT OUTPUT
============================================================
	Enforcement level (0–6)
Urban population rate	0.004626
	(0.0178423)
GDP per capita (US$)	0.0000168
	(0.0000172)
Government effectiveness	0.5562192
	(0.861514)
Electricity cost (USD/kWh)	3.5815242
	(2.5400588)
Corruption Perceptions Index	-0.026824
	(0.043989)
Climate adaptation index (ND-GAIN)	0.0022163
	(0.061221)
Observations	54
Log-likelihood	-98.30
AIC	220.6
BIC	244.5

Table 5 (Journal Format) saved to: your/path/to/reproducibility package/Output/Table_5_Appendix_A.csv
your/path/to/venv/lib/site-packages/statsmodels/base/model.py:604: ConvergenceWarning: Maximum Likelihood optimization failed to converge. Check mle_retvals
  warnings.warn("Maximum Likelihood optimization failed to "

Part 5: Multicollinearity Check - VIF (Table 6)¶

This section calculates the Variance Inflation Factor (VIF) for all independent variables. A constant is explicitly added to ensure version-stable and mathematically correct VIF values.

In [11]:
# Data Analysis after the first regression

import statsmodels.api as sm
from statsmodels.stats.outliers_influence import variance_inflation_factor

# Ensure output folder exists
current_dir = os.getcwd()
project_root = os.path.dirname(current_dir)
output_folder = os.path.join(project_root, 'Output')
os.makedirs(output_folder, exist_ok=True)

# IMPORTANT FIX: Add a constant to X before calculating VIF
X_vif = sm.add_constant(X)

# Calculate VIF
vif_data = pd.DataFrame()
vif_data["Variable"] = X_vif.columns
vif_data["VIF"] = [variance_inflation_factor(X_vif.values, i) for i in range(X_vif.shape[1])]

# Drop the constant row from the final output table (we only care about variables)
vif_data = vif_data[vif_data["Variable"] != "const"].reset_index(drop=True)

print("VIF Values (with constant included in calculation):")
print(vif_data)

# Save VIF table as Table 6 (CSV format)
vif_data.to_csv(os.path.join(output_folder, 'Table_6_Appendix_A.csv'), index=False)
print(f"Table 6 saved to: {os.path.join(output_folder, 'Table_6_Appendix_A.csv')}")

# Print Y value counts (for diagnostic purposes, not saved)
print("\nY Value Counts:")
print(Y.value_counts().sort_index())
VIF Values (with constant included in calculation):
                         Variable        VIF
0           Urban_Population_Rate   2.030943
1                  GDP_Per_Capita   3.256067
2        Government_Effectiveness   7.030097
3     Cost_of_Electricity_USD/KWH   1.866269
4    Corruption_Perceptions_Index  10.657408
5  Climate_Change_Global_Adoption   6.316088
Table 6 saved to: your/path/to/reproducibility package/Output/Table_6_Appendix_A.csv

Y Value Counts:
0.0     7
1.0     5
2.0     6
3.0     8
4.0     9
5.0    10
6.0     9
Name: Passive_Design_Checklist_Number, dtype: int64

Part 6: Correlation Matrix Heatmap (Figure 5)¶

This section computes the pairwise correlation matrix for all independent variables and saves the heatmap as Fig 5_Appendix_A.png.

In [12]:
# Check for Corr

import seaborn as sns

# Ensure output folder exists
current_dir = os.getcwd()
project_root = os.path.dirname(current_dir)
output_folder = os.path.join(project_root, 'Output')
os.makedirs(output_folder, exist_ok=True)

# Compute correlation matrix
corr_matrix = X.corr().round(2)
plt.figure(figsize=(8, 6))
sns.set(font_scale=0.9)

sns.heatmap(
    corr_matrix,
    annot=True,           # show numeric correlation values
    cmap='coolwarm',      # red–blue gradient
    center=0,             # zero-centered color scale
    linewidths=0.5,       # thin lines between cells
    cbar_kws={'shrink': 0.8, 'label': 'Correlation Coefficient'}
)

plt.title('Correlation Heatmap of Independent Variables', fontsize=13, pad=10)
plt.tight_layout()

# Save figure as Figure 5 (high resolution)
plt.savefig(os.path.join(output_folder, 'Fig 5_Appendix_A.png'),
            dpi=300, bbox_inches='tight')

# Display the plot
plt.show()
No description has been provided for this image

Part 7: Random Forest Feature Selection (Table 7 & Figure 6)¶

This section uses a Random Forest Classifier to assess the importance of the control variables (excluding electricity cost, which is forced into the model). Variables with an importance score above the mean threshold are selected. The feature importances are saved as Table_7_Appendix_A.csv and plotted in Fig 6_Appendix_A.png.

In [13]:
# Machine Learning, RF for variable selection (excluding Cost_of_Electricity)

import numpy as np
from sklearn.ensemble import RandomForestClassifier

# Ensure output folder exists
current_dir = os.getcwd()
project_root = os.path.dirname(current_dir)
output_folder = os.path.join(project_root, 'Output')
os.makedirs(output_folder, exist_ok=True)

print("=== PART 1: RANDOM FOREST FEATURE SELECTION (Excluding Cost_of_Electricity) ===")
print("=" * 60)
print("Note: 'Cost_of_Electricity_USD/KWH' is forced to stay in final model per domain knowledge.\n")

Y = journal_dataset_cleaned["Passive_Design_Checklist_Number"]

X_candidates = journal_dataset_cleaned[[
    "Urban_Population_Rate", "GDP_Per_Capita", 
    "Government_Effectiveness", "Corruption_Perceptions_Index",
    "Climate_Change_Global_Adoption"
]]

print(f"Y distribution:\n{Y.value_counts().sort_index()}")
print(f"Total samples: {len(Y)}, Candidate features: {X_candidates.shape[1]}")

rf_model = RandomForestClassifier(
    n_estimators=200,
    random_state=42,
    oob_score=True,
    max_features='sqrt'
)

rf_model.fit(X_candidates, Y)

importance_df = pd.DataFrame({
    'Variable': X_candidates.columns,
    'Importance': rf_model.feature_importances_
}).sort_values('Importance', ascending=False)

print("\nRandom Forest Feature Importance (on candidate variables):")
print(importance_df.to_string(index=False, float_format='%.4f'))

# Save Table 7: Feature Importance
importance_df.to_csv(os.path.join(output_folder, 'Table_7_Appendix_A.csv'),
                     index=False, float_format='%.4f')
print(f"\nTable 7 saved to: {os.path.join(output_folder, 'Table_7_Appendix_A.csv')}")

print(f"\nNumber of candidate features: {len(importance_df)}")
print(f"Sum of importance scores: {importance_df['Importance'].sum():.4f}")
importance_threshold = importance_df['Importance'].mean()
print(f"Importance threshold (mean): {importance_threshold:.4f}")

selected_from_rf = importance_df[importance_df['Importance'] > importance_threshold]['Variable'].tolist()

final_variables = ["Cost_of_Electricity_USD/KWH"] + selected_from_rf

print(f"\nSelected variables by RF (importance > mean): {selected_from_rf}")
print(f"\nFINAL VARIABLES FOR MODEL (must include): {final_variables}")
print(f"Total variables: {len(final_variables)} (1 forced + {len(selected_from_rf)} selected)")

# Plot and save Figure 6
plt.figure(figsize=(10, 6))
colors = ['steelblue' if var in selected_from_rf else 'lightgray' for var in importance_df['Variable']]
bars = plt.barh(range(len(importance_df)), importance_df['Importance'], color=colors)
plt.axvline(x=importance_threshold, color='red', linestyle='--', label=f'Threshold (Avg): {importance_threshold:.4f}')
plt.yticks(range(len(importance_df)), importance_df['Variable'])
plt.xlabel('Feature Importance')
plt.title('Random Forest Feature Importance (Candidate Variables Only)')
plt.legend()
plt.gca().invert_yaxis()
plt.tight_layout()

# Save Figure 6
plt.savefig(os.path.join(output_folder, 'Fig 6_Appendix_A.png'),
            dpi=300, bbox_inches='tight')
print(f"Figure 6 saved to: {os.path.join(output_folder, 'Fig 6_Appendix_A.png')}")

plt.show()
=== PART 1: RANDOM FOREST FEATURE SELECTION (Excluding Cost_of_Electricity) ===
============================================================
Note: 'Cost_of_Electricity_USD/KWH' is forced to stay in final model per domain knowledge.

Y distribution:
0.0     7
1.0     5
2.0     6
3.0     8
4.0     9
5.0    10
6.0     9
Name: Passive_Design_Checklist_Number, dtype: int64
Total samples: 54, Candidate features: 5
your/path/to/venv/lib/site-packages/sklearn/base.py:441: UserWarning: X does not have valid feature names, but RandomForestClassifier was fitted with feature names
  warnings.warn(
Random Forest Feature Importance (on candidate variables):
                      Variable  Importance
                GDP_Per_Capita      0.2181
         Urban_Population_Rate      0.2121
Climate_Change_Global_Adoption      0.2019
      Government_Effectiveness      0.1937
  Corruption_Perceptions_Index      0.1743

Table 7 saved to: your/path/to/reproducibility package/Output/Table_7_Appendix_A.csv

Number of candidate features: 5
Sum of importance scores: 1.0000
Importance threshold (mean): 0.2000

Selected variables by RF (importance > mean): ['GDP_Per_Capita', 'Urban_Population_Rate', 'Climate_Change_Global_Adoption']

FINAL VARIABLES FOR MODEL (must include): ['Cost_of_Electricity_USD/KWH', 'GDP_Per_Capita', 'Urban_Population_Rate', 'Climate_Change_Global_Adoption']
Total variables: 4 (1 forced + 3 selected)
Figure 6 saved to: your/path/to/reproducibility package/Output/Fig 6_Appendix_A.png
No description has been provided for this image

Part 8: Principal Component Analysis (Tables 8 & 9, Figures 7 & 8)¶

This section standardizes the five control variables and performs Principal Component Analysis (PCA). It outputs the explained variance ratios (Table 8), component loadings/weights (Table 9), an explained variance scree plot (Figure 7), and a heatmap of the PCA loadings (Figure 8).

In [14]:
# PCA on the 5 control variables (excluding electricity cost)

from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
import seaborn as sns


# Ensure output folder exists
current_dir = os.getcwd()
project_root = os.path.dirname(current_dir)
output_folder = os.path.join(project_root, 'Output')
os.makedirs(output_folder, exist_ok=True)

# Define the 5 control variables
control_vars = [
    "GDP_Per_Capita",
    "Government_Effectiveness",
    "Corruption_Perceptions_Index",
    "Climate_Change_Global_Adoption",
    "Urban_Population_Rate"
]

# Extract data
X_controls = journal_dataset_cleaned[control_vars].dropna()  # ensure no missing
print(f"Sample size for PCA: {len(X_controls)}")

# Standardize (PCA on correlation matrix)
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X_controls)

# Perform PCA
pca = PCA()
pca.fit(X_scaled)

# Explained variance
explained_variance = pca.explained_variance_ratio_
cumulative_variance = np.cumsum(explained_variance)

print("\n=== PCA Results ===")
print(f"Explained variance ratio per component: {explained_variance.round(4)}")
print(f"Cumulative variance: {cumulative_variance.round(4)}")

# Save Table 8: PCA Results (explained variance + cumulative)
pca_summary_df = pd.DataFrame({
    'Principal_Component': [f'PC{i+1}' for i in range(len(explained_variance))],
    'Explained_Variance_Ratio': explained_variance,
    'Cumulative_Variance': cumulative_variance
})
pca_summary_df.to_csv(os.path.join(output_folder, 'Table_8_Appendix_A.csv'),
                      index=False, float_format='%.4f')
print(f"\nTable 8 saved to: {os.path.join(output_folder, 'Table_8_Appendix_A.csv')}")

# Loadings (component coefficients / weights)
loadings = pd.DataFrame(
    pca.components_.T,
    columns=[f"PC{i+1}" for i in range(len(control_vars))],
    index=control_vars
)

print("\nComponent coefficients (weights to compute PC scores):")
print(loadings.round(4))

# Save Table 9: Component coefficients (weights)
loadings.to_csv(os.path.join(output_folder, 'Table_9_Appendix_A.csv'),
                index=True, float_format='%.4f')
print(f"Table 9 saved to: {os.path.join(output_folder, 'Table_9_Appendix_A.csv')}")

# Correlation loadings (more interpretable: correlation between var and PC)
corr_loadings = loadings.multiply(np.sqrt(explained_variance), axis=1)
print("\nCorrelation loadings (correlation between variable and PC):")
print(corr_loadings.round(4))

# Figure 7: Explained variance plot (bar + cumulative curve)
plt.figure(figsize=(8,5))
plt.bar(range(1, len(explained_variance)+1), explained_variance, alpha=0.6, label='Individual')
plt.step(range(1, len(cumulative_variance)+1), cumulative_variance, where='mid', label='Cumulative', color='red')
plt.xlabel('Principal Component')
plt.ylabel('Explained Variance Ratio')
plt.title('PCA Explained Variance')
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig(os.path.join(output_folder, 'Figure_7_Appendix_A.png'), dpi=300, bbox_inches='tight')
print(f"Figure 7 saved to: {os.path.join(output_folder, 'Figure_7_Appendix_A.png')}")
plt.show()

# Figure 8: Heatmap of correlation loadings
plt.figure(figsize=(8,6))
sns.heatmap(corr_loadings, annot=True, cmap='coolwarm', center=0, fmt='.3f')
plt.title('PCA Loadings (Correlation between Variables and PCs)')
plt.tight_layout()
plt.savefig(os.path.join(output_folder, 'Figure_8_Appendix_A.png'), dpi=300, bbox_inches='tight')
print(f"Figure_8_Appendix_A saved to: {os.path.join(output_folder, 'Figure_8_Appendix_A.png')}")
plt.show()
Sample size for PCA: 54

=== PCA Results ===
Explained variance ratio per component: [0.8074 0.0995 0.0518 0.0271 0.0141]
Cumulative variance: [0.8074 0.9069 0.9588 0.9859 1.    ]

Table 8 saved to: your/path/to/reproducibility package/Output/Table_8_Appendix_A.csv

Component coefficients (weights to compute PC scores):
                                   PC1     PC2     PC3     PC4     PC5
GDP_Per_Capita                  0.4423  0.1635  0.8599  0.1942 -0.0213
Government_Effectiveness        0.4673  0.2602 -0.1475 -0.6826 -0.4756
Corruption_Perceptions_Index    0.4736  0.2524 -0.2531 -0.0828  0.8007
Climate_Change_Global_Adoption  0.4666  0.0720 -0.4179  0.6878 -0.3597
Urban_Population_Rate           0.3794 -0.9147  0.0090 -0.1282  0.0535
Table 9 saved to: your/path/to/reproducibility package/Output/Table_9_Appendix_A.csv

Correlation loadings (correlation between variable and PC):
                                   PC1     PC2     PC3     PC4     PC5
GDP_Per_Capita                  0.3975  0.0516  0.1958  0.0319 -0.0025
Government_Effectiveness        0.4199  0.0821 -0.0336 -0.1123 -0.0566
Corruption_Perceptions_Index    0.4255  0.0796 -0.0576 -0.0136  0.0952
Climate_Change_Global_Adoption  0.4193  0.0227 -0.0952  0.1132 -0.0428
Urban_Population_Rate           0.3409 -0.2886  0.0020 -0.0211  0.0064
Figure 7 saved to: your/path/to/reproducibility package/Output/Figure_7_Appendix_A.png
No description has been provided for this image
Figure_8_Appendix_A saved to: your/path/to/reproducibility package/Output/Figure_8_Appendix_A.png
No description has been provided for this image

Part 9: Baseline Model Comparison - Electricity vs PC1 (Table 10)¶

This section fits two separate Ordered Logit models: one using only electricity cost as the predictor, and the other using only the first principal component (PC1) of the control variables. It extracts the coefficients, standard errors, and model fit statistics, saving the comparison as Table_10_Appendix_A.csv.

In [15]:
# Compare models: Electricity only vs PC1 only

import pandas as pd
import numpy as np
from statsmodels.miscmodels.ordinal_model import OrderedModel
import os

# Ensure output folder exists
current_dir = os.getcwd()
project_root = os.path.dirname(current_dir)
output_folder = os.path.join(project_root, 'Output')
os.makedirs(output_folder, exist_ok=True)

# Prepare variables
pc1_scores = pca.transform(X_scaled)[:, 0]
elec = journal_dataset_cleaned.loc[X_controls.index, "Cost_of_Electricity_USD/KWH"]
Y = journal_dataset_cleaned.loc[X_controls.index, "Passive_Design_Checklist_Number"]

# Fit models
m_elec = OrderedModel(Y, pd.DataFrame(elec), distr='logit').fit(method='bfgs', disp=False)
m_pc1 = OrderedModel(Y, pd.DataFrame(pc1_scores, columns=['PC1']), distr='logit').fit(method='bfgs', disp=False)

# Print AIC and BIC (for interactive check)
print(f"Electricity only - AIC: {m_elec.aic:.2f}, BIC: {m_elec.bic:.2f}")
print(f"PC1 only         - AIC: {m_pc1.aic:.2f}, BIC: {m_pc1.bic:.2f}")

# Extract results for both models into a summary table
def extract_model_results(model, model_name):
    params = model.params
    bse = model.bse
    pvalues = model.pvalues
    conf_int = model.conf_int()
    n_params = len(params)
    df = pd.DataFrame({
        'Model': [model_name] * n_params,
        'Parameter': params.index,
        'Coefficient': params.values,
        'Std_Error': bse.values,
        'P_Value': pvalues.values,
        'CI_2.5%': conf_int.iloc[:, 0].values,
        'CI_97.5%': conf_int.iloc[:, 1].values
    })
    return df, model.aic, model.bic

df_elec, aic_elec, bic_elec = extract_model_results(m_elec, 'Electricity only')
df_pc1, aic_pc1, bic_pc1 = extract_model_results(m_pc1, 'PC1 only')

# Combine
df_combined = pd.concat([df_elec, df_pc1], ignore_index=True)

# Add AIC and BIC as constant columns for each row (for clarity)
df_combined['AIC'] = [aic_elec] * len(df_elec) + [aic_pc1] * len(df_pc1)
df_combined['BIC'] = [bic_elec] * len(df_elec) + [bic_pc1] * len(df_pc1)

# Save Table 10
df_combined.to_csv(os.path.join(output_folder, 'Table_10_Appendix_A.csv'),
                   index=False, float_format='%.4f')
print(f"Table 10 saved to: {os.path.join(output_folder, 'Table_10_Appendix_A.csv')}")
Electricity only - AIC: 214.22, BIC: 228.14
PC1 only         - AIC: 213.42, BIC: 227.34
Table 10 saved to: your/path/to/reproducibility package/Output/Table_10_Appendix_A.csv

Part 10: Final Model Comparison (Table 11)¶

This section estimates four competing Ordered Logit models based on the features selected by RF and PCA: (1) Electricity only, (2) PC1 only, (3) Electricity + RF-selected controls, and (4) Electricity + PC1. It compares their Bayesian Information Criterion (BIC) values and saves the results as Table_11_Appendix_A.csv.

In [16]:
# Final regression models after RF and PCA parallel analysis

# Ensure output folder exists
current_dir = os.getcwd()
project_root = os.path.dirname(current_dir)
output_folder = os.path.join(project_root, 'Output')
os.makedirs(output_folder, exist_ok=True)

Y = journal_dataset_cleaned["Passive_Design_Checklist_Number"]
X_elec = journal_dataset_cleaned[["Cost_of_Electricity_USD/KWH"]]

# Model 1: Electricity only
m1 = OrderedModel(Y, X_elec, distr='logit').fit(method='bfgs', disp=False)
print("Model 1: Electricity only")
print(m1.summary())

# Model 2: PC1 only (using previously computed pc1_scores)
pc1_scores = pca.transform(X_scaled)[:, 0]  # computed earlier
X_pc1 = pd.DataFrame(pc1_scores, columns=["PC1"])
m2 = OrderedModel(Y, X_pc1, distr='logit').fit(method='bfgs', disp=False)
print("\nModel 2: PC1 only")
print(m2.summary())

# Model 3: Electricity + RF-selected controls (GDP, Urban, Climate)
rf_selected = ["Cost_of_Electricity_USD/KWH", "GDP_Per_Capita", 
               "Urban_Population_Rate", "Climate_Change_Global_Adoption"]
X_rf = journal_dataset_cleaned[rf_selected]
m3 = OrderedModel(Y, X_rf, distr='logit').fit(method='bfgs', disp=False)
print("\nModel 3: Electricity + RF-selected controls")
print(m3.summary())

# Model 4: Electricity + PC1
X_elec_pc1 = pd.concat([
    X_elec.reset_index(drop=True),
    X_pc1.reset_index(drop=True)
], axis=1)
m4 = OrderedModel(Y, X_elec_pc1, distr='logit').fit(method='bfgs', disp=False)
print("\nModel 4: Electricity + PC1")
print(m4.summary())

# ============================================================
# Compare BIC and Prepare Table 11
# ============================================================

print("\n=== BIC Comparison ===")
print(f"Model 1 (Electricity):        BIC = {m1.bic:.2f}")
print(f"Model 2 (PC1):                BIC = {m2.bic:.2f}")
print(f"Model 3 (Elec + RF selected): BIC = {m3.bic:.2f}")
print(f"Model 4 (Elec + PC1):         BIC = {m4.bic:.2f}")

# Create a DataFrame for Table 11 (BIC only)
bic_data = [
    {"Model": "Model 1 (Electricity)", "BIC": f"{m1.bic:.2f}"},
    {"Model": "Model 2 (PC1)", "BIC": f"{m2.bic:.2f}"},
    {"Model": "Model 3 (Elec + RF selected)", "BIC": f"{m3.bic:.2f}"},
    {"Model": "Model 4 (Elec + PC1)", "BIC": f"{m4.bic:.2f}"}
]

df_bic = pd.DataFrame(bic_data)

# Save Table 11
table11_path = os.path.join(output_folder, 'Table_11_Appendix_A.csv')
df_bic.to_csv(table11_path, index=False)
print(f"\nTable 11 saved to: {table11_path}")
Model 1: Electricity only
                                    OrderedModel Results                                   
===========================================================================================
Dep. Variable:     Passive_Design_Checklist_Number   Log-Likelihood:                -100.11
Model:                                OrderedModel   AIC:                             214.2
Method:                         Maximum Likelihood   BIC:                             228.1
Date:                             Tue, 24 Nov 2026                                         
Time:                                     13:08:50                                         
No. Observations:                               54                                         
Df Residuals:                                   47                                         
Df Model:                                        7                                         
===============================================================================================
                                  coef    std err          z      P>|z|      [0.025      0.975]
-----------------------------------------------------------------------------------------------
Cost_of_Electricity_USD/KWH     4.9793      1.904      2.616      0.009       1.248       8.710
0.0/1.0                        -1.1278      0.494     -2.284      0.022      -2.096      -0.160
1.0/2.0                        -0.3452      0.428     -0.807      0.420      -1.183       0.493
2.0/3.0                        -0.4579      0.386     -1.185      0.236      -1.215       0.299
3.0/4.0                        -0.3351      0.332     -1.010      0.313      -0.986       0.315
4.0/5.0                        -0.2505      0.312     -0.804      0.421      -0.861       0.360
5.0/6.0                         0.0382      0.297      0.129      0.898      -0.544       0.620
===============================================================================================

Model 2: PC1 only
                                    OrderedModel Results                                   
===========================================================================================
Dep. Variable:     Passive_Design_Checklist_Number   Log-Likelihood:                -99.709
Model:                                OrderedModel   AIC:                             213.4
Method:                         Maximum Likelihood   BIC:                             227.3
Date:                             Tue, 24 Nov 2026                                         
Time:                                     13:08:50                                         
No. Observations:                               54                                         
Df Residuals:                                   47                                         
Df Model:                                        7                                         
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
PC1            0.3539      0.126      2.815      0.005       0.108       0.600
0.0/1.0       -2.1018      0.425     -4.944      0.000      -2.935      -1.269
1.0/2.0       -0.3683      0.430     -0.856      0.392      -1.212       0.475
2.0/3.0       -0.4778      0.388     -1.231      0.218      -1.238       0.283
3.0/4.0       -0.3318      0.332     -0.999      0.318      -0.983       0.319
4.0/5.0       -0.2373      0.311     -0.763      0.446      -0.847       0.372
5.0/6.0        0.0764      0.295      0.259      0.796      -0.503       0.655
==============================================================================

Model 3: Electricity + RF-selected controls
                                    OrderedModel Results                                   
===========================================================================================
Dep. Variable:     Passive_Design_Checklist_Number   Log-Likelihood:                -98.545
Model:                                OrderedModel   AIC:                             217.1
Method:                         Maximum Likelihood   BIC:                             237.0
Date:                             Tue, 24 Nov 2026                                         
Time:                                     13:08:50                                         
No. Observations:                               54                                         
Df Residuals:                                   44                                         
Df Model:                                       10                                         
==================================================================================================
                                     coef    std err          z      P>|z|      [0.025      0.975]
--------------------------------------------------------------------------------------------------
Cost_of_Electricity_USD/KWH        3.2029      2.410      1.329      0.184      -1.520       7.926
GDP_Per_Capita                  1.705e-05   1.52e-05      1.120      0.263   -1.28e-05    4.69e-05
Urban_Population_Rate              0.0050      0.018      0.285      0.776      -0.030       0.040
Climate_Change_Global_Adoption    -0.0039      0.047     -0.083      0.934      -0.096       0.089
0.0/1.0                           -0.8890      2.001     -0.444      0.657      -4.811       3.034
1.0/2.0                           -0.3482      0.429     -0.812      0.417      -1.189       0.492
2.0/3.0                           -0.4429      0.387     -1.144      0.253      -1.202       0.316
3.0/4.0                           -0.2933      0.333     -0.881      0.378      -0.946       0.359
4.0/5.0                           -0.2022      0.311     -0.650      0.516      -0.812       0.407
5.0/6.0                            0.0973      0.297      0.327      0.744      -0.486       0.680
==================================================================================================

Model 4: Electricity + PC1
                                    OrderedModel Results                                   
===========================================================================================
Dep. Variable:     Passive_Design_Checklist_Number   Log-Likelihood:                -98.913
Model:                                OrderedModel   AIC:                             213.8
Method:                         Maximum Likelihood   BIC:                             229.7
Date:                             Tue, 24 Nov 2026                                         
Time:                                     13:08:50                                         
No. Observations:                               54                                         
Df Residuals:                                   46                                         
Df Model:                                        8                                         
===============================================================================================
                                  coef    std err          z      P>|z|      [0.025      0.975]
-----------------------------------------------------------------------------------------------
Cost_of_Electricity_USD/KWH     2.8732      2.307      1.245      0.213      -1.648       7.395
PC1                             0.2382      0.155      1.538      0.124      -0.065       0.542
0.0/1.0                        -1.5891      0.584     -2.721      0.007      -2.734      -0.445
1.0/2.0                        -0.3438      0.428     -0.803      0.422      -1.183       0.495
2.0/3.0                        -0.4408      0.387     -1.139      0.255      -1.199       0.317
3.0/4.0                        -0.2970      0.332     -0.894      0.371      -0.948       0.354
4.0/5.0                        -0.2117      0.311     -0.680      0.496      -0.822       0.398
5.0/6.0                         0.0687      0.296      0.232      0.816      -0.511       0.648
===============================================================================================

=== BIC Comparison ===
Model 1 (Electricity):        BIC = 228.14
Model 2 (PC1):                BIC = 227.34
Model 3 (Elec + RF selected): BIC = 236.98
Model 4 (Elec + PC1):         BIC = 229.74

Table 11 saved to: your/path/to/reproducibility package/Output/Table_11_Appendix_A.csv

Part 11: Detailed Analysis of Model 1 & AME (Tables 1 & 2)¶

This section provides a comprehensive analysis of Model 1 (Electricity only). It formats the regression results into a standard journal table (Table 1) and calculates the Average Marginal Effects (AME) to show how a $0.10 increase in electricity price shifts the probability distribution across the 7 enforcement levels (Table 2).

In [17]:
# ============================================================================
# Detailed analysis of Model 1 (Electricity only) - FINAL VERSION
# ============================================================================


# Ensure output folder exists
current_dir = os.getcwd()
project_root = os.path.dirname(current_dir)
output_folder = os.path.join(project_root, 'Output')
os.makedirs(output_folder, exist_ok=True)

print("\n" + "="*80)
print("DETAILED ANALYSIS OF MODEL 1: ELECTRICITY ONLY")
print("="*80)

# 1. Coefficient interpretation
coef = m1.params['Cost_of_Electricity_USD/KWH']
se = m1.bse['Cost_of_Electricity_USD/KWH']
z = coef / se
pvalue = m1.pvalues['Cost_of_Electricity_USD/KWH']

# FIXED: Standard Economics convention (*** p<0.01, ** p<0.05, * p<0.10)
stars = '***' if pvalue < 0.01 else '**' if pvalue < 0.05 else '*' if pvalue < 0.10 else ''

# 2. Model fit statistics
loglik = m1.llf
aic = m1.aic
bic = m1.bic

# Compute McFadden R-squared
freq = Y.value_counts(normalize=True).sort_index()
null_ll = np.sum(freq * np.log(freq)) * len(Y)
mcfadden_r2 = 1 - (loglik / null_ll)

# ============================================================================
# 3. TABLE 1: FINAL JOURNAL FORMAT
# ============================================================================
print("\n" + "="*80)
print("TABLE 1: FINAL RESULTS (JOURNAL FORMAT)")
print("="*80)

# Format the coefficient and standard error strings
coef_str = f"{coef:.3f}{stars}"
se_str = f"({se:.3f})"

# Build the exact table structure requested
table1_data = [
    {"Variable": "", "Model": "Enforcement level (0–6)"},
    {"Variable": "Electricity cost (USD/kWh)", "Model": coef_str},
    {"Variable": "", "Model": se_str},
    {"Variable": "Observations", "Model": str(int(len(Y)))},
    {"Variable": "Log-likelihood", "Model": f"{loglik:.2f}"},
    {"Variable": "AIC", "Model": f"{aic:.1f}"},
    {"Variable": "BIC", "Model": f"{bic:.1f}"},
    {"Variable": "McFadden pseudo R²", "Model": f"{mcfadden_r2:.3f}"}
]

df_table1 = pd.DataFrame(table1_data)

# Print to console
for row in table1_data:
    print(f"{row['Variable']}\t{row['Model']}")

# Save Table 1
table1_path = os.path.join(output_folder, 'Table_1.csv')
df_table1.to_csv(table1_path, index=False)
print(f"\nTable 1 saved to: {table1_path}")


# ============================================================================
# 4. TABLE 2: AVERAGE MARGINAL EFFECTS (AME) - UNCHANGED
# ============================================================================
print("\n" + "="*80)
print("AVERAGE MARGINAL EFFECTS (AME) FOR MODEL 1")
print("="*80)

# Define AME function
def calculate_ame(model_result, data, var_name, change=0.1):
    baseline_probs = model_result.predict()
    data_mod = data.copy()
    data_mod[var_name] = data_mod[var_name] + change
    new_probs = model_result.predict(exog=data_mod)
    ame = new_probs.mean(axis=0) - baseline_probs.mean(axis=0)
    return ame, baseline_probs.mean(axis=0), new_probs.mean(axis=0)

elec_sd = journal_dataset_cleaned["Cost_of_Electricity_USD/KWH"].std()
changes = [
    (0.05, "$0.05 increase"),
    (0.10, "$0.10 increase (typical policy change)"),
    (elec_sd, f"1 SD increase ({elec_sd:.3f} USD/kWh)")
]

# Store AME results for CSV export
ame_results = []

for change_amt, desc in changes:
    ame, baseline, new = calculate_ame(m1, X_elec, 'Cost_of_Electricity_USD/KWH', change_amt)
    df_ame = pd.DataFrame({
        'Change_Amount': [desc] * 7,
        'Level': range(7),
        'Baseline_Prob_%': baseline * 100,
        'New_Prob_%': new * 100,
        'AME_%': ame * 100
    })
    ame_results.append(df_ame)
    print(f"\n{desc}:")
    print(df_ame.round(2).to_string(index=False))

# Combine and save Table 2 (exactly as before)
ame_combined_df = pd.concat(ame_results, ignore_index=True)
ame_combined_df.insert(0, 'Section', 'AME')
ame_combined_df.to_csv(os.path.join(output_folder, 'Table_2_AME.csv'), index=False, float_format='%.2f')

print(f"\nTable 2 saved to: {os.path.join(output_folder, 'Table_2_AME.csv')}")
print("\nAll files saved successfully.")
================================================================================
DETAILED ANALYSIS OF MODEL 1: ELECTRICITY ONLY
================================================================================

================================================================================
TABLE 1: FINAL RESULTS (JOURNAL FORMAT)
================================================================================
	Enforcement level (0–6)
Electricity cost (USD/kWh)	4.979***
	(1.904)
Observations	54
Log-likelihood	-100.11
AIC	214.2
BIC	228.1
McFadden pseudo R²	0.035

Table 1 saved to: your/path/to/reproducibility package/Output/Table_1.csv

================================================================================
AVERAGE MARGINAL EFFECTS (AME) FOR MODEL 1
================================================================================

$0.05 increase:
 Change_Amount  Level  Baseline_Prob_%  New_Prob_%  AME_%
$0.05 increase      0            13.07       10.56  -2.51
$0.05 increase      1             9.79        8.39  -1.40
$0.05 increase      2            12.05       10.88  -1.16
$0.05 increase      3            15.94       15.34  -0.60
$0.05 increase      4            16.88       17.42   0.54
$0.05 increase      5            16.77       18.63   1.85
$0.05 increase      6            15.51       18.79   3.28

$0.10 increase (typical policy change):
                         Change_Amount  Level  Baseline_Prob_%  New_Prob_%  AME_%
$0.10 increase (typical policy change)      0            13.07        8.47  -4.59
$0.10 increase (typical policy change)      1             9.79        7.08  -2.71
$0.10 increase (typical policy change)      2            12.05        9.63  -2.42
$0.10 increase (typical policy change)      3            15.94       14.42  -1.52
$0.10 increase (typical policy change)      4            16.88       17.57   0.70
$0.10 increase (typical policy change)      5            16.77       20.30   3.52
$0.10 increase (typical policy change)      6            15.51       22.54   7.03

1 SD increase (0.131 USD/kWh):
                Change_Amount  Level  Baseline_Prob_%  New_Prob_%  AME_%
1 SD increase (0.131 USD/kWh)      0            13.07        7.36  -5.71
1 SD increase (0.131 USD/kWh)      1             9.79        6.31  -3.47
1 SD increase (0.131 USD/kWh)      2            12.05        8.83  -3.22
1 SD increase (0.131 USD/kWh)      3            15.94       13.70  -2.24
1 SD increase (0.131 USD/kWh)      4            16.88       17.46   0.59
1 SD increase (0.131 USD/kWh)      5            16.77       21.20   4.43
1 SD increase (0.131 USD/kWh)      6            15.51       25.13   9.62

Table 2 saved to: your/path/to/reproducibility package/Output/Table_2_AME.csv

All files saved successfully.

Part 12: Visualization of AME and Probability Shift (Figure 3)¶

This section visualizes the Average Marginal Effects (AME) of a $0.10 electricity price increase. It generates a two-panel figure: the left panel shows the percentage point change at each enforcement level, and the right panel compares the baseline probability distribution with the post-increase distribution. The output is saved as Fig 3.png.

In [18]:
# ============================================================================
# Visualization: Figure 3
# ============================================================================


# Ensure output folder exists
current_dir = os.getcwd()
project_root = os.path.dirname(current_dir)
output_folder = os.path.join(project_root, 'Output')
os.makedirs(output_folder, exist_ok=True)

# ----------------------------------------------------------------------------
# Recompute AME for $0.10 increase (needed because these variables were
# removed from the Table 1 cell)
# ----------------------------------------------------------------------------
def calculate_ame(model_result, data, var_name, change=0.1):
    baseline_probs = model_result.predict()
    data_mod = data.copy()
    data_mod[var_name] = data_mod[var_name] + change
    new_probs = model_result.predict(exog=data_mod)
    ame = new_probs.mean(axis=0) - baseline_probs.mean(axis=0)
    return ame, baseline_probs.mean(axis=0), new_probs.mean(axis=0)

ame_010, baseline_010, new_010 = calculate_ame(
    m1, X_elec, 'Cost_of_Electricity_USD/KWH', 0.10
)

# ----------------------------------------------------------------------------
# Plot
# ----------------------------------------------------------------------------
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 6))

# Left: AME bars
colors = ['red' if val < 0 else 'green' for val in ame_010 * 100]
bars = ax1.bar(range(7), ame_010 * 100, color=colors, alpha=0.7, edgecolor='black')
ax1.axhline(y=0, color='black', linewidth=0.5)
ax1.set_xlabel('Enforcement Level (0-6)')
ax1.set_ylabel('Probability Change (Percentage Points)')
ax1.set_title('Average Marginal Effect: $0.10 Electricity Price Increase')
ax1.set_xticks(range(7))
ax1.grid(True, alpha=0.3, axis='y')
for bar in bars:
    height = bar.get_height()
    ax1.text(bar.get_x() + bar.get_width()/2., height,
             f'{height:.2f}%', ha='center', va='bottom' if height >= 0 else 'top')

# Right: Probability shift
x = np.arange(7)
width = 0.35
ax2.bar(x - width/2, baseline_010 * 100, width, label='Baseline', alpha=0.7, color='steelblue')
ax2.bar(x + width/2, new_010 * 100, width, label='After $0.10 Increase', alpha=0.7, color='orange')
ax2.set_xlabel('Enforcement Level (0-6)')
ax2.set_ylabel('Probability (%)')
ax2.set_title('Probability Distribution Shift')
ax2.set_xticks(x)
ax2.legend()
ax2.grid(True, alpha=0.3, axis='y')

plt.tight_layout()

# Save Figure 3
plt.savefig(os.path.join(output_folder, 'Fig 3.png'),
            dpi=300, bbox_inches='tight')
print(f"Figure 3 saved to: {os.path.join(output_folder, 'Fig 3.png')}")

plt.show()

print("\n" + "="*80)
print("END OF DETAILED ANALYSIS FOR MODEL 1")
print("="*80)
Figure 3 saved to: your/path/to/reproducibility package/Output/Fig 3.png
No description has been provided for this image
================================================================================
END OF DETAILED ANALYSIS FOR MODEL 1
================================================================================

Part 13: Non-Linear Electricity Cost Model (Table 12)¶

This section tests for a non-linear relationship between electricity costs and enforcement levels. It fits an Ordered Logit model using the centered electricity cost and its squared term. The formatted regression results are saved as Table_12_Appendix_B.csv.

In [19]:
# ============================================================================
# Model 5: Electricity cost with quadratic term (centered)
# ============================================================================

from statsmodels.miscmodels.ordinal_model import OrderedModel

# Ensure output folder exists
current_dir = os.getcwd()
project_root = os.path.dirname(current_dir)
output_folder = os.path.join(project_root, 'Output')
os.makedirs(output_folder, exist_ok=True)

# Prepare centered electricity cost
elec = journal_dataset_cleaned["Cost_of_Electricity_USD/KWH"]
elec_mean = elec.mean()
elec_c = elec - elec_mean
elec_c_sq = elec_c ** 2

Y = journal_dataset_cleaned["Passive_Design_Checklist_Number"]
X_quad = pd.DataFrame({
    "elec_c": elec_c,
    "elec_c_sq": elec_c_sq
})

# Fit ordered logit
model_quad = OrderedModel(Y, X_quad, distr='logit')
result_quad = model_quad.fit(method='bfgs', disp=False)

print("="*80)
print("ORDERED LOGIT WITH QUADRATIC ELECTRICITY TERM (centered)")
print("="*80)
print(result_quad.summary())

# ============================================================
# SAVE TABLE 12 (Appendix B): Quadratic Model Results
# ============================================================

print("\n" + "="*80)
print("SAVING TABLE 12: NON-LINEAR ELECTRICITY COST ORDERED LOGIT MODEL")
print("="*80)

# Extract coefficients and standard errors
coef_c = result_quad.params['elec_c']
se_c = result_quad.bse['elec_c']
pval_c = result_quad.pvalues['elec_c']

coef_sq = result_quad.params['elec_c_sq']
se_sq = result_quad.bse['elec_c_sq']
pval_sq = result_quad.pvalues['elec_c_sq']

# Helper function for significance stars (Standard Economics convention)
def get_stars(p):
    if p < 0.01: return '***'
    elif p < 0.05: return '**'
    elif p < 0.10: return '*'
    else: return ''

stars_c = get_stars(pval_c)
stars_sq = get_stars(pval_sq)

# Helper function to format numbers exactly as requested (e.g., 8.752, -30.448)
def fmt(val, decimals=3):
    return f"{val:.{decimals}f}"

# Build the journal-formatted table data
table12_data = [
    {"Variable": "", "Model": "Enforcement level (0–6)"},
    {"Variable": "Electricity cost (USD/kWh)", "Model": f"{fmt(coef_c)}{stars_c}"},
    {"Variable": "", "Model": f"({fmt(se_c)})"},
    {"Variable": "Electricity cost squared", "Model": f"{fmt(coef_sq)}{stars_sq}"},
    {"Variable": "", "Model": f"({fmt(se_sq)})"},
    {"Variable": "Observations", "Model": str(int(result_quad.nobs))},
    {"Variable": "Log-likelihood", "Model": f"{result_quad.llf:.2f}"},
    {"Variable": "AIC", "Model": f"{result_quad.aic:.1f}"},
    {"Variable": "BIC", "Model": f"{result_quad.bic:.1f}"}
]

df_table12 = pd.DataFrame(table12_data)

# Print to console
for row in table12_data:
    print(f"{row['Variable']}\t{row['Model']}")

# Save to CSV
table12_path = os.path.join(output_folder, 'Table_12_Appendix_B.csv')
df_table12.to_csv(table12_path, index=False)

print(f"\nTable 12 saved to: {table12_path}")
================================================================================
ORDERED LOGIT WITH QUADRATIC ELECTRICITY TERM (centered)
================================================================================
                                    OrderedModel Results                                   
===========================================================================================
Dep. Variable:     Passive_Design_Checklist_Number   Log-Likelihood:                -97.422
Model:                                OrderedModel   AIC:                             210.8
Method:                         Maximum Likelihood   BIC:                             226.8
Date:                             Tue, 24 Nov 2026                                         
Time:                                     13:08:53                                         
No. Observations:                               54                                         
Df Residuals:                                   46                                         
Df Model:                                        8                                         
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
elec_c         8.7254      2.552      3.419      0.001       3.724      13.727
elec_c_sq    -30.1211     13.429     -2.243      0.025     -56.441      -3.802
0.0/1.0       -2.6965      0.532     -5.066      0.000      -3.740      -1.653
1.0/2.0       -0.2714      0.425     -0.638      0.523      -1.105       0.562
2.0/3.0       -0.3823      0.388     -0.986      0.324      -1.142       0.378
3.0/4.0       -0.2591      0.333     -0.778      0.437      -0.912       0.394
4.0/5.0       -0.1672      0.311     -0.538      0.591      -0.777       0.442
5.0/6.0        0.0847      0.294      0.288      0.773      -0.492       0.661
==============================================================================

================================================================================
SAVING TABLE 12: NON-LINEAR ELECTRICITY COST ORDERED LOGIT MODEL
================================================================================
	Enforcement level (0–6)
Electricity cost (USD/kWh)	8.725***
	(2.552)
Electricity cost squared	-30.121**
	(13.429)
Observations	54
Log-likelihood	-97.42
AIC	210.8
BIC	226.8

Table 12 saved to: your/path/to/reproducibility package/Output/Table_12_Appendix_B.csv

Part 14: Average Marginal Effects for Quadratic Model (Table 13)¶

This section calculates the Average Marginal Effects (AME) for the non-linear (quadratic) model, evaluating probability shifts at $0.05, $0.10, and a 1-standard-deviation increase in electricity cost. It prints a policy implications summary and saves the detailed level-by-level results as Table_13_Appendix_B_extended.csv.

In [20]:
# ============================================================================
# AME for Quadratic Model (Electricity cost with squared term)
# ============================================================================

# Ensure output folder exists
current_dir = os.getcwd()
project_root = os.path.dirname(current_dir)
output_folder = os.path.join(project_root, 'Output')
os.makedirs(output_folder, exist_ok=True)

print("\n" + "="*80)
print("AVERAGE MARGINAL EFFECTS (AME) FOR QUADRATIC MODEL")
print("="*80)

# Extract mean of electricity for centering (needed to construct exog)
elec_mean = elec.mean()

def calculate_ame_quad(model_result, data_original, var_name_original, mean_val, change=0.1):
    """
    Calculate AME for quadratic model where predictors are centered.
    model_result: fitted OrderedModel
    data_original: DataFrame containing the original electricity cost (column name = var_name_original)
    mean_val: mean used for centering
    change: increase in original units (USD/kWh)
    """
    # Baseline: centered variables
    elec_c_baseline = data_original[var_name_original] - mean_val
    elec_c_sq_baseline = elec_c_baseline ** 2
    X_baseline = pd.DataFrame({
        'elec_c': elec_c_baseline,
        'elec_c_sq': elec_c_sq_baseline
    })
    baseline_probs = model_result.predict(exog=X_baseline)
    
    # New: add change to original electricity, then re-center
    elec_new = data_original[var_name_original] + change
    elec_c_new = elec_new - mean_val
    elec_c_sq_new = elec_c_new ** 2
    X_new = pd.DataFrame({
        'elec_c': elec_c_new,
        'elec_c_sq': elec_c_sq_new
    })
    new_probs = model_result.predict(exog=X_new)
    
    ame = new_probs.mean(axis=0) - baseline_probs.mean(axis=0)
    return ame, baseline_probs.mean(axis=0), new_probs.mean(axis=0)

# Prepare original electricity data
elec_original = journal_dataset_cleaned[["Cost_of_Electricity_USD/KWH"]]

# Define changes to evaluate
elec_sd = elec_original["Cost_of_Electricity_USD/KWH"].std()
changes = [
    (0.05, "$0.05 increase"),
    (0.10, "$0.10 increase (typical policy change)"),
    (elec_sd, f"1 SD increase ({elec_sd:.3f} USD/kWh)")
]

# Store AME results for CSV export
ame_results_quad = []

for change_amt, desc in changes:
    ame, baseline, new = calculate_ame_quad(
        result_quad, elec_original, 'Cost_of_Electricity_USD/KWH', 
        mean_val=elec_mean, change=change_amt
    )
    df_ame = pd.DataFrame({
        'Level': range(7),
        'Baseline_Prob_%': baseline * 100,
        'New_Prob_%': new * 100,
        'AME_%': ame * 100
    })
    df_ame.insert(0, 'Change_Amount', desc)
    ame_results_quad.append(df_ame)
    print(f"\n{desc}:")
    print(df_ame.round(2).to_string(index=False))

# Combine all AME results
ame_combined_quad_df = pd.concat(ame_results_quad, ignore_index=True)

# Policy implications for $0.10 increase
ame_010, baseline_010, new_010 = calculate_ame_quad(
    result_quad, elec_original, 'Cost_of_Electricity_USD/KWH', 
    mean_val=elec_mean, change=0.10
)

print("\n" + "="*80)
print("POLICY IMPLICATIONS SUMMARY (Quadratic Model, $0.10 increase)")
print("="*80)

baseline_high = np.sum(baseline_010[4:]) * 100
new_high = np.sum(new_010[4:]) * 100
increase_high = new_high - baseline_high

baseline_low = np.sum(baseline_010[:3]) * 100
new_low = np.sum(new_010[:3]) * 100
decrease_low = baseline_low - new_low

print(f"   Probability of high enforcement (Levels 4-6):")
print(f"   • Baseline: {baseline_high:.1f}%")
print(f"   • After $0.10 increase: {new_high:.1f}%")
print(f"   • Change: +{increase_high:.1f} percentage points")
print()
print(f"   Probability of low enforcement (Levels 0-2):")
print(f"   • Baseline: {baseline_low:.1f}%")
print(f"   • After $0.10 increase: {new_low:.1f}%")
print(f"   • Change: -{decrease_low:.1f} percentage points")
print()
print(f"   Net shift from low to high enforcement: {increase_high + decrease_low:.1f} percentage points")

# Optional: Compare with linear model's AME for $0.10 (from earlier, stored as ame_010_linear)
# If ame_010_linear exists in memory, we can compare. But we can also re-calc quickly.
print("\n" + "="*80)
print("COMPARISON WITH LINEAR MODEL (Model 1)")
print("="*80)
print("Linear model AME for $0.10 (from previous output):")
print("   Level 0: -4.38%, Level 1: -2.58%, Level 2: -2.30%, Level 3: -1.45%,")
print("   Level 4: +0.65%, Level 5: +3.38%, Level 6: +6.67%")
print("   Net shift low->high: 20.0 percentage points")
print()
print("Quadratic model AME for $0.10 (above):")
# Print the AME_% from the $0.10 increase table
ame_010_df = ame_results_quad[1]  # second item is $0.10 increase
print("   " + ", ".join([f"Level {i}: {ame_010_df.loc[i,'AME_%']:+.2f}%" for i in range(7)]))
print(f"   Net shift low->high: {increase_high + decrease_low:.1f} percentage points")

# Save combined AME results as Table 13
table15_path = os.path.join(output_folder, 'Table_13_Appendix_B_extended.csv')
ame_combined_quad_df.to_csv(table15_path, index=False, float_format='%.4f')
print(f"\nTable 13 saved to: {table15_path}")
================================================================================
AVERAGE MARGINAL EFFECTS (AME) FOR QUADRATIC MODEL
================================================================================

$0.05 increase:
 Change_Amount  Level  Baseline_Prob_%  New_Prob_%  AME_%
$0.05 increase      0            13.32        8.59  -4.73
$0.05 increase      1             9.76        7.67  -2.09
$0.05 increase      2            11.65       10.51  -1.14
$0.05 increase      3            15.40       15.64   0.24
$0.05 increase      4            17.09       18.88   1.79
$0.05 increase      5            17.24       20.04   2.80
$0.05 increase      6            15.54       18.67   3.13

$0.10 increase (typical policy change):
                         Change_Amount  Level  Baseline_Prob_%  New_Prob_%  AME_%
$0.10 increase (typical policy change)      0            13.32        6.88  -6.44
$0.10 increase (typical policy change)      1             9.76        6.39  -3.37
$0.10 increase (typical policy change)      2            11.65        9.24  -2.41
$0.10 increase (typical policy change)      3            15.40       14.83  -0.57
$0.10 increase (typical policy change)      4            17.09       19.42   2.33
$0.10 increase (typical policy change)      5            17.24       21.96   4.72
$0.10 increase (typical policy change)      6            15.54       21.28   5.75

1 SD increase (0.131 USD/kWh):
                Change_Amount  Level  Baseline_Prob_%  New_Prob_%  AME_%
1 SD increase (0.131 USD/kWh)      0            13.32        6.92  -6.41
1 SD increase (0.131 USD/kWh)      1             9.76        6.06  -3.70
1 SD increase (0.131 USD/kWh)      2            11.65        8.68  -2.97
1 SD increase (0.131 USD/kWh)      3            15.40       14.17  -1.23
1 SD increase (0.131 USD/kWh)      4            17.09       19.23   2.14
1 SD increase (0.131 USD/kWh)      5            17.24       22.54   5.30
1 SD increase (0.131 USD/kWh)      6            15.54       22.40   6.87

================================================================================
POLICY IMPLICATIONS SUMMARY (Quadratic Model, $0.10 increase)
================================================================================
   Probability of high enforcement (Levels 4-6):
   • Baseline: 49.9%
   • After $0.10 increase: 62.7%
   • Change: +12.8 percentage points

   Probability of low enforcement (Levels 0-2):
   • Baseline: 34.7%
   • After $0.10 increase: 22.5%
   • Change: -12.2 percentage points

   Net shift from low to high enforcement: 25.0 percentage points

================================================================================
COMPARISON WITH LINEAR MODEL (Model 1)
================================================================================
Linear model AME for $0.10 (from previous output):
   Level 0: -4.38%, Level 1: -2.58%, Level 2: -2.30%, Level 3: -1.45%,
   Level 4: +0.65%, Level 5: +3.38%, Level 6: +6.67%
   Net shift low->high: 20.0 percentage points

Quadratic model AME for $0.10 (above):
   Level 0: -6.44%, Level 1: -3.37%, Level 2: -2.41%, Level 3: -0.57%, Level 4: +2.33%, Level 5: +4.72%, Level 6: +5.75%
   Net shift low->high: 25.0 percentage points

Table 13 saved to: your/path/to/reproducibility package/Output/Table_13_Appendix_B_extended.csv

Part 15: AME Comparison - Linear vs Quadratic Models (Figure 9)¶

This section recalculates the Average Marginal Effects for both the linear (Model 1) and quadratic (Model 5) specifications using identical probability prediction methods. It visualizes the differences in probability shifts across enforcement levels in a grouped bar chart, saving the output as Fig 9_Appendix_B.png.

In [21]:
# ============================================================================
# Recompute AME for Linear and Quadratic models (consistent with which='prob')
# ============================================================================


# Ensure output folder exists
current_dir = os.getcwd()
project_root = os.path.dirname(current_dir)
output_folder = os.path.join(project_root, 'Output')
os.makedirs(output_folder, exist_ok=True)

# Ensure m1 and result_quad are available
if 'm1' not in dir():
    print("Error: m1 (linear model) not found. Please run Model 1 first.")
if 'result_quad' not in dir():
    print("Error: result_quad (quadratic model) not found. Please run Model 5 first.")

# Prepare data
elec_data = journal_dataset_cleaned[['Cost_of_Electricity_USD/KWH']]
elec_mean = elec_data['Cost_of_Electricity_USD/KWH'].mean()

# Linear model AME
def ame_linear(model, data, var_name, change=0.10):
    X_base = data[[var_name]]
    probs_base = model.predict(exog=X_base, which='prob')
    X_new = data[[var_name]] + change
    probs_new = model.predict(exog=X_new, which='prob')
    # Convert to numpy if needed
    if hasattr(probs_base, 'values'):
        probs_base = probs_base.values
        probs_new = probs_new.values
    ame = probs_new.mean(axis=0) - probs_base.mean(axis=0)
    return ame * 100  # percentage points

# Quadratic model AME
def ame_quadratic(model, data, var_name, mean_center, change=0.10):
    # Baseline
    elec_c = data[var_name] - mean_center
    X_base = pd.DataFrame({'elec_c': elec_c, 'elec_c_sq': elec_c**2})
    probs_base = model.predict(exog=X_base, which='prob')
    # New
    elec_new = data[var_name] + change
    elec_c_new = elec_new - mean_center
    X_new = pd.DataFrame({'elec_c': elec_c_new, 'elec_c_sq': elec_c_new**2})
    probs_new = model.predict(exog=X_new, which='prob')
    # Convert to numpy if needed
    if hasattr(probs_base, 'values'):
        probs_base = probs_base.values
        probs_new = probs_new.values
    ame = probs_new.mean(axis=0) - probs_base.mean(axis=0)
    return ame * 100

# Compute
ame_linear_consistent = ame_linear(m1, elec_data, 'Cost_of_Electricity_USD/KWH', change=0.10)
ame_quad = ame_quadratic(result_quad, elec_data, 'Cost_of_Electricity_USD/KWH', elec_mean, change=0.10)

# Print results
print("Linear Model AME (% points, $0.10 increase):")
for i, val in enumerate(ame_linear_consistent):
    print(f"  Level {i}: {val:+.2f}%")
print("\nQuadratic Model AME (% points, $0.10 increase):")
for i, val in enumerate(ame_quad):
    print(f"  Level {i}: {val:+.2f}%")

# Plot
levels = np.arange(7)
x = np.arange(7)
width = 0.35

fig, ax = plt.subplots(figsize=(12, 6))
bars1 = ax.bar(x - width/2, ame_linear_consistent, width, label='Linear Model', 
               color='#2c7bb6', alpha=0.8)
bars2 = ax.bar(x + width/2, ame_quad, width, label='Quadratic Model', 
               color='#fdae61', alpha=0.8)

ax.axhline(0, color='black', linewidth=0.8)
ax.set_xlabel('Enforcement Level', fontsize=12)
ax.set_ylabel('Average Marginal Effect (percentage points)', fontsize=12)
ax.set_title('AME for $0.10 Electricity Cost Increase: Linear vs Quadratic', fontsize=14)
ax.set_xticks(x)
ax.set_xticklabels([f'Level {i}' for i in range(7)])
ax.legend()

# Add value labels
for bars in [bars1, bars2]:
    for bar in bars:
        height = bar.get_height()
        if height >= 0:
            va = 'bottom'
            offset = 0.2
        else:
            va = 'top'
            offset = -0.2
        ax.text(bar.get_x() + bar.get_width()/2., height + offset, 
                f'{height:.2f}', ha='center', va=va, fontsize=9)

ax.grid(axis='y', linestyle='--', alpha=0.5)
plt.tight_layout()

# Save Figure 9
plt.savefig(os.path.join(output_folder, 'Fig 9_Appendix_B.png'), dpi=300, bbox_inches='tight')
print(f"\nFigure 9 saved to: {os.path.join(output_folder, 'Fig 9_Appendix_B.png')}")

plt.show()
Linear Model AME (% points, $0.10 increase):
  Level 0: -4.59%
  Level 1: -2.71%
  Level 2: -2.42%
  Level 3: -1.52%
  Level 4: +0.70%
  Level 5: +3.52%
  Level 6: +7.03%

Quadratic Model AME (% points, $0.10 increase):
  Level 0: -6.44%
  Level 1: -3.37%
  Level 2: -2.41%
  Level 3: -0.57%
  Level 4: +2.33%
  Level 5: +4.72%
  Level 6: +5.75%

Figure 9 saved to: your/path/to/reproducibility package/Output/Fig 9_Appendix_B.png
No description has been provided for this image

Part 16: Data Preparation for Individual Mechanism Regressions¶

This section creates a new dataset (df_enforcement_items) designed for the binary logistic regressions. It extracts the six specific passive design enforcement mechanisms, converts them into binary indicators (1 for "Yes" or "Yes, but inconsistently", and 0 otherwise), and appends the electricity cost variable.

In [22]:
# Build new dataset for six binary enforcement mechanisms + electricity cost
import pandas as pd
import numpy as np

# Define the six mechanism descriptions as they appear in the original columns
mechanism_descriptions = [
    "Passive Design Enforcement Mechanisms: Checklist of Passive Design",
    "Passive Design Enforcement Mechanisms: Thermal Transmittance or Insulation Calculations for Building Envelope",
    "Passive Design Enforcement Mechanisms: Solar Heat Gains Calculations for Building Envelope",
    "Passive Design Enforcement Mechanisms: Glazing Factors for Fenestration",
    "Passive Design Enforcement Mechanisms: Permanent Shading",
    "Passive Design Enforcement Mechanisms: Air Barrier, Air Leakage, or Air Infiltration"
]

# Function to find the exact column name (case-insensitive partial match)
def find_column(df, pattern):
    for col in df.columns:
        if pattern.lower() in col.lower():
            return col
    return None

# Find actual column names in journal_dataset3
mechanism_cols = []
for desc in mechanism_descriptions:
    col_name = find_column(journal_dataset3, desc)
    if col_name is None:
        raise ValueError(f"Column not found for pattern: {desc}")
    mechanism_cols.append(col_name)

# Electricity cost column
elec_original_name = find_column(journal_dataset3, "Cost_of_Electricity_2023_USD/KWH")
if elec_original_name is None:
    raise ValueError("Electricity cost column not found.")
elec_new_name = "Cost_of_Electricity_USD/KWH"

# Create new dataframe
df_enforcement_items = pd.DataFrame()

# Process each mechanism: binary encoding (1 for 'yes' or 'yes, but inconsistently', else 0)
for i, col in enumerate(mechanism_cols):
    # Convert to string, strip, lowercase
    series = journal_dataset3[col].astype(str).str.strip().str.lower()
    # Replace 'nan' or 'none' with empty string to avoid false positives
    series = series.replace(['nan', 'none'], '')
    # Binary: contains 'yes' -> 1, else 0
    binary = series.str.contains('yes', na=False).astype(int)
    # Simplified column name: remove the prefix
    simplified = mechanism_descriptions[i].replace("Passive Design Enforcement Mechanisms: ", "").strip()
    df_enforcement_items[simplified] = binary
    # Print summary
    print(f"{simplified} (original: {col}) -> 1: {binary.sum()}, 0: {len(binary)-binary.sum()}")

# Add electricity cost (rename column)
df_enforcement_items[elec_new_name] = journal_dataset3[elec_original_name]
Checklist of Passive Design (original: Passive Design Enforcement Mechanisms: Checklist of Passive Design) -> 1: 25, 0: 29
Thermal Transmittance or Insulation Calculations for Building Envelope (original: Passive Design Enforcement Mechanisms: Thermal Transmittance or Insulation Calculations for Building Envelope) -> 1: 42, 0: 12
Solar Heat Gains Calculations for Building Envelope (original: Passive Design Enforcement Mechanisms: Solar Heat Gains Calculations for Building Envelope) -> 1: 32, 0: 22
Glazing Factors for Fenestration (original: Passive Design Enforcement Mechanisms: Glazing Factors for Fenestration) -> 1: 34, 0: 20
Permanent Shading (original: Passive Design Enforcement Mechanisms: Permanent Shading) -> 1: 22, 0: 32
Air Barrier, Air Leakage, or Air Infiltration (original: Passive Design Enforcement Mechanisms: Air Barrier, Air Leakage, or Air Infiltration) -> 1: 26, 0: 28

Part 17: Binary Logistic Regressions - Selected & First Three Mechanisms¶

This section estimates binary logistic regressions to examine the effect of electricity costs on individual passive design enforcement mechanisms. It first tests the three target mechanisms (Glazing, Thermal, Solar) and then evaluates the first three mechanisms in the dataset (Checklist, Thermal, Solar), printing the odds ratios and confidence intervals for exploratory comparison.

In [23]:
# Part 1: Binary logistic regression for first three mechanisms
from statsmodels.discrete.discrete_model import Logit
import statsmodels.api as sm
import pandas as pd
import numpy as np
import os# ============================================================================
# Binary logistic regression for 3 selected mechanisms (Fig 3-5)
# ============================================================================
from statsmodels.discrete.discrete_model import Logit
import statsmodels.api as sm
import pandas as pd
import numpy as np
import os

# Ensure output folder exists
current_dir = os.getcwd()
project_root = os.path.dirname(current_dir)
output_folder = os.path.join(project_root, 'Output')
os.makedirs(output_folder, exist_ok=True)

# Selected 3 mechanisms (note: column name must match df_enforcement_items exactly)
mechanisms_selected = [
    "Glazing Factors for Fenestration",
    "Thermal Transmittance or Insulation Calculations for Building Envelope",
    "Solar Heat Gains Calculations for Building Envelope"
]

# Prepare data
X = df_enforcement_items[['Cost_of_Electricity_USD/KWH']]
X = sm.add_constant(X)

results_selected = []

for mech in mechanisms_selected:
    y = df_enforcement_items[mech]
    model = Logit(y, X)
    result = model.fit(disp=0)

    coef = result.params['Cost_of_Electricity_USD/KWH']
    se = result.bse['Cost_of_Electricity_USD/KWH']
    pval = result.pvalues['Cost_of_Electricity_USD/KWH']
    ci = result.conf_int().loc['Cost_of_Electricity_USD/KWH']
    odds_ratio = np.exp(coef)
    ci_odds = np.exp(ci)

    results_selected.append({
        'Mechanism': mech,
        'Coef': coef,
        'StdErr': se,
        'p-value': pval,
        'Odds_Ratio': odds_ratio,
        'CI_low': ci_odds[0],
        'CI_high': ci_odds[1],
        'N_1': y.sum(),
        'N_0': len(y) - y.sum()
    })

    print(f"\n{'='*60}")
    print(f"Dependent Variable: {mech}")
    print(f"  1's: {y.sum()}, 0's: {len(y)-y.sum()}")
    print(result.summary2())
    print(f"Odds Ratio for electricity: {odds_ratio:.4f} (95% CI: {ci_odds[0]:.4f}, {ci_odds[1]:.4f})")

print("\n" + "="*60)
print("SUMMARY FOR SELECTED 3 MECHANISMS (Fig 3-5)")
print("="*60)
summary_selected = pd.DataFrame(results_selected)
print(summary_selected.round(4).to_string(index=False))

# Ensure output folder exists
current_dir = os.getcwd()
project_root = os.path.dirname(current_dir)
output_folder = os.path.join(project_root, 'Output')
os.makedirs(output_folder, exist_ok=True)

# Define first three mechanism column names (as created in df_enforcement_items)
mechanisms_part1 = [
    "Checklist of Passive Design",
    "Thermal Transmittance or Insulation Calculations for Building Envelope",
    "Solar Heat Gains Calculations for Building Envelope"
]

# Prepare data
X = df_enforcement_items[['Cost_of_Electricity_USD/KWH']]
X = sm.add_constant(X)

results_part1 = []

for mech in mechanisms_part1:
    y = df_enforcement_items[mech]
    # Fit logistic regression
    model = Logit(y, X)
    result = model.fit(disp=0)
    
    coef = result.params['Cost_of_Electricity_USD/KWH']
    se = result.bse['Cost_of_Electricity_USD/KWH']
    pval = result.pvalues['Cost_of_Electricity_USD/KWH']
    ci = result.conf_int().loc['Cost_of_Electricity_USD/KWH']
    odds_ratio = np.exp(coef)
    ci_odds = np.exp(ci)
    
    results_part1.append({
        'Mechanism': mech,
        'Coef': coef,
        'StdErr': se,
        'p-value': pval,
        'Odds_Ratio': odds_ratio,
        'CI_low': ci_odds[0],
        'CI_high': ci_odds[1],
        'N_1': y.sum(),
        'N_0': len(y) - y.sum()
    })
    
    print(f"\n{'='*60}")
    print(f"Dependent Variable: {mech}")
    print(f"  1's: {y.sum()}, 0's: {len(y)-y.sum()}")
    print(result.summary2())
    print(f"Odds Ratio for electricity: {odds_ratio:.4f} (95% CI: {ci_odds[0]:.4f}, {ci_odds[1]:.4f})")

print("\n" + "="*60)
print("SUMMARY FOR FIRST THREE MECHANISMS")
print("="*60)
summary_part1 = pd.DataFrame(results_part1)
print(summary_part1.round(4).to_string(index=False))
============================================================
Dependent Variable: Glazing Factors for Fenestration
  1's: 34, 0's: 20
                                 Results: Logit
=================================================================================
Model:              Logit                            Pseudo R-squared: 0.289     
Dependent Variable: Glazing Factors for Fenestration AIC:              54.6256   
Date:               2026-11-24 13:08                 BIC:              58.6036   
No. Observations:   54                               Log-Likelihood:   -25.313   
Df Model:           1                                LL-Null:          -35.594   
Df Residuals:       52                               LLR p-value:      5.7705e-06
Converged:          1.0000                           Scale:            1.0000    
No. Iterations:     7.0000                                                       
----------------------------------------------------------------------------------
                               Coef.   Std.Err.     z     P>|z|    [0.025   0.975]
----------------------------------------------------------------------------------
const                         -1.6637    0.6425  -2.5894  0.0096  -2.9229  -0.4044
Cost_of_Electricity_USD/KWH   14.8027    4.3741   3.3842  0.0007   6.2296  23.3757
=================================================================================

Odds Ratio for electricity: 2683576.1577 (95% CI: 507.5417, 14189142850.6953)

============================================================
Dependent Variable: Thermal Transmittance or Insulation Calculations for Building Envelope
  1's: 42, 0's: 12
                                                    Results: Logit
======================================================================================================================
Model:              Logit                                                                  Pseudo R-squared: 0.174    
Dependent Variable: Thermal Transmittance or Insulation Calculations for Building Envelope AIC:              51.2662  
Date:               2026-11-24 13:08                                                       BIC:              55.2441  
No. Observations:   54                                                                     Log-Likelihood:   -23.633  
Df Model:           1                                                                      LL-Null:          -28.604  
Df Residuals:       52                                                                     LLR p-value:      0.0016154
Converged:          1.0000                                                                 Scale:            1.0000   
No. Iterations:     7.0000                                                                                            
------------------------------------------------------------------------------------------------------------------------------
                                        Coef.          Std.Err.            z            P>|z|           [0.025          0.975]
------------------------------------------------------------------------------------------------------------------------------
const                                  -0.3106           0.6019         -0.5161         0.6058         -1.4902          0.8690
Cost_of_Electricity_USD/KWH            11.3479           4.5701          2.4831         0.0130          2.3908         20.3051
======================================================================================================================

Odds Ratio for electricity: 84789.7808 (95% CI: 10.9219, 658249486.4943)

============================================================
Dependent Variable: Solar Heat Gains Calculations for Building Envelope
  1's: 32, 0's: 22
                                          Results: Logit
===================================================================================================
Model:              Logit                                               Pseudo R-squared: 0.140    
Dependent Variable: Solar Heat Gains Calculations for Building Envelope AIC:              66.7573  
Date:               2026-11-24 13:08                                    BIC:              70.7353  
No. Observations:   54                                                  Log-Likelihood:   -31.379  
Df Model:           1                                                   LL-Null:          -36.499  
Df Residuals:       52                                                  LLR p-value:      0.0013743
Converged:          1.0000                                              Scale:            1.0000   
No. Iterations:     6.0000                                                                         
-------------------------------------------------------------------------------------------------------
                                     Coef.      Std.Err.        z        P>|z|       [0.025      0.975]
-------------------------------------------------------------------------------------------------------
const                               -0.9855       0.5387     -1.8295     0.0673     -2.0413      0.0703
Cost_of_Electricity_USD/KWH          8.2395       2.9968      2.7494     0.0060      2.3659     14.1131
===================================================================================================

Odds Ratio for electricity: 3787.6307 (95% CI: 10.6534, 1346626.1337)

============================================================
SUMMARY FOR SELECTED 3 MECHANISMS (Fig 3-5)
============================================================
                                                             Mechanism    Coef  StdErr  p-value   Odds_Ratio   CI_low      CI_high  N_1  N_0
                                      Glazing Factors for Fenestration 14.8027  4.3741   0.0007 2683576.1577 507.5417 1.418914e+10   34   20
Thermal Transmittance or Insulation Calculations for Building Envelope 11.3479  4.5701   0.0130   84789.7808  10.9219 6.582495e+08   42   12
                   Solar Heat Gains Calculations for Building Envelope  8.2395  2.9968   0.0060    3787.6307  10.6534 1.346626e+06   32   22

============================================================
Dependent Variable: Checklist of Passive Design
  1's: 25, 0's: 29
                              Results: Logit
==========================================================================
Model:               Logit                       Pseudo R-squared: 0.019  
Dependent Variable:  Checklist of Passive Design AIC:              77.1528
Date:                2026-11-24 13:08            BIC:              81.1308
No. Observations:    54                          Log-Likelihood:   -36.576
Df Model:            1                           LL-Null:          -37.282
Df Residuals:        52                          LLR p-value:      0.23497
Converged:           1.0000                      Scale:            1.0000 
No. Iterations:      4.0000                                               
--------------------------------------------------------------------------
                             Coef.  Std.Err.    z    P>|z|   [0.025 0.975]
--------------------------------------------------------------------------
const                        0.3103   0.4761  0.6517 0.5146 -0.6229 1.2435
Cost_of_Electricity_USD/KWH -2.5540   2.1969 -1.1625 0.2450 -6.8599 1.7520
==========================================================================

Odds Ratio for electricity: 0.0778 (95% CI: 0.0010, 5.7658)

============================================================
Dependent Variable: Thermal Transmittance or Insulation Calculations for Building Envelope
  1's: 42, 0's: 12
                                                    Results: Logit
======================================================================================================================
Model:              Logit                                                                  Pseudo R-squared: 0.174    
Dependent Variable: Thermal Transmittance or Insulation Calculations for Building Envelope AIC:              51.2662  
Date:               2026-11-24 13:08                                                       BIC:              55.2441  
No. Observations:   54                                                                     Log-Likelihood:   -23.633  
Df Model:           1                                                                      LL-Null:          -28.604  
Df Residuals:       52                                                                     LLR p-value:      0.0016154
Converged:          1.0000                                                                 Scale:            1.0000   
No. Iterations:     7.0000                                                                                            
------------------------------------------------------------------------------------------------------------------------------
                                        Coef.          Std.Err.            z            P>|z|           [0.025          0.975]
------------------------------------------------------------------------------------------------------------------------------
const                                  -0.3106           0.6019         -0.5161         0.6058         -1.4902          0.8690
Cost_of_Electricity_USD/KWH            11.3479           4.5701          2.4831         0.0130          2.3908         20.3051
======================================================================================================================

Odds Ratio for electricity: 84789.7808 (95% CI: 10.9219, 658249486.4943)

============================================================
Dependent Variable: Solar Heat Gains Calculations for Building Envelope
  1's: 32, 0's: 22
                                          Results: Logit
===================================================================================================
Model:              Logit                                               Pseudo R-squared: 0.140    
Dependent Variable: Solar Heat Gains Calculations for Building Envelope AIC:              66.7573  
Date:               2026-11-24 13:08                                    BIC:              70.7353  
No. Observations:   54                                                  Log-Likelihood:   -31.379  
Df Model:           1                                                   LL-Null:          -36.499  
Df Residuals:       52                                                  LLR p-value:      0.0013743
Converged:          1.0000                                              Scale:            1.0000   
No. Iterations:     6.0000                                                                         
-------------------------------------------------------------------------------------------------------
                                     Coef.      Std.Err.        z        P>|z|       [0.025      0.975]
-------------------------------------------------------------------------------------------------------
const                               -0.9855       0.5387     -1.8295     0.0673     -2.0413      0.0703
Cost_of_Electricity_USD/KWH          8.2395       2.9968      2.7494     0.0060      2.3659     14.1131
===================================================================================================

Odds Ratio for electricity: 3787.6307 (95% CI: 10.6534, 1346626.1337)

============================================================
SUMMARY FOR FIRST THREE MECHANISMS
============================================================
                                                             Mechanism    Coef  StdErr  p-value  Odds_Ratio  CI_low      CI_high  N_1  N_0
                                           Checklist of Passive Design -2.5540  2.1969    0.245      0.0778  0.0010 5.765800e+00   25   29
Thermal Transmittance or Insulation Calculations for Building Envelope 11.3479  4.5701    0.013  84789.7808 10.9219 6.582495e+08   42   12
                   Solar Heat Gains Calculations for Building Envelope  8.2395  2.9968    0.006   3787.6307 10.6534 1.346626e+06   32   22

Part 18: Binary Logistic Regressions - Last Three Mechanisms¶

This section completes the exploratory binary logistic regressions by evaluating the remaining three mechanisms (Glazing Factors, Permanent Shading, and Air Barrier). It prints the model summaries and odds ratios for comparison.

In [24]:
# Part 2: Binary logistic regression for last three mechanisms
from statsmodels.discrete.discrete_model import Logit
import statsmodels.api as sm
import pandas as pd
import numpy as np
import os

# Ensure output folder exists
current_dir = os.getcwd()
project_root = os.path.dirname(current_dir)
output_folder = os.path.join(project_root, 'Output')
os.makedirs(output_folder, exist_ok=True)

# Define last three mechanism column names
mechanisms_part2 = [
    "Glazing Factors for Fenestration",
    "Permanent Shading",
    "Air Barrier, Air Leakage, or Air Infiltration"
]

# Prepare data
X = df_enforcement_items[['Cost_of_Electricity_USD/KWH']]
X = sm.add_constant(X)

results_part2 = []

for mech in mechanisms_part2:
    y = df_enforcement_items[mech]
    model = Logit(y, X)
    result = model.fit(disp=0)
    
    coef = result.params['Cost_of_Electricity_USD/KWH']
    se = result.bse['Cost_of_Electricity_USD/KWH']
    pval = result.pvalues['Cost_of_Electricity_USD/KWH']
    ci = result.conf_int().loc['Cost_of_Electricity_USD/KWH']
    odds_ratio = np.exp(coef)
    ci_odds = np.exp(ci)
    
    results_part2.append({
        'Mechanism': mech,
        'Coef': coef,
        'StdErr': se,
        'p-value': pval,
        'Odds_Ratio': odds_ratio,
        'CI_low': ci_odds[0],
        'CI_high': ci_odds[1],
        'N_1': y.sum(),
        'N_0': len(y) - y.sum()
    })
    
    print(f"\n{'='*60}")
    print(f"Dependent Variable: {mech}")
    print(f"  1's: {y.sum()}, 0's: {len(y)-y.sum()}")
    print(result.summary2())
    print(f"Odds Ratio for electricity: {odds_ratio:.4f} (95% CI: {ci_odds[0]:.4f}, {ci_odds[1]:.4f})")

print("\n" + "="*60)
print("SUMMARY FOR LAST THREE MECHANISMS")
print("="*60)
summary_part2 = pd.DataFrame(results_part2)
print(summary_part2.round(4).to_string(index=False))
============================================================
Dependent Variable: Glazing Factors for Fenestration
  1's: 34, 0's: 20
                                 Results: Logit
=================================================================================
Model:              Logit                            Pseudo R-squared: 0.289     
Dependent Variable: Glazing Factors for Fenestration AIC:              54.6256   
Date:               2026-11-24 13:08                 BIC:              58.6036   
No. Observations:   54                               Log-Likelihood:   -25.313   
Df Model:           1                                LL-Null:          -35.594   
Df Residuals:       52                               LLR p-value:      5.7705e-06
Converged:          1.0000                           Scale:            1.0000    
No. Iterations:     7.0000                                                       
----------------------------------------------------------------------------------
                               Coef.   Std.Err.     z     P>|z|    [0.025   0.975]
----------------------------------------------------------------------------------
const                         -1.6637    0.6425  -2.5894  0.0096  -2.9229  -0.4044
Cost_of_Electricity_USD/KWH   14.8027    4.3741   3.3842  0.0007   6.2296  23.3757
=================================================================================

Odds Ratio for electricity: 2683576.1577 (95% CI: 507.5417, 14189142850.6953)

============================================================
Dependent Variable: Permanent Shading
  1's: 22, 0's: 32
                              Results: Logit
===========================================================================
Model:                   Logit                Pseudo R-squared:    0.044   
Dependent Variable:      Permanent Shading    AIC:                 73.8205 
Date:                    2026-11-24 13:08     BIC:                 77.7984 
No. Observations:        54                   Log-Likelihood:      -34.910 
Df Model:                1                    LL-Null:             -36.499 
Df Residuals:            52                   LLR p-value:         0.074688
Converged:               1.0000               Scale:               1.0000  
No. Iterations:          5.0000                                            
---------------------------------------------------------------------------
                             Coef.  Std.Err.    z    P>|z|   [0.025  0.975]
---------------------------------------------------------------------------
const                       -1.0945   0.5086 -2.1518 0.0314 -2.0914 -0.0976
Cost_of_Electricity_USD/KWH  3.8683   2.2378  1.7286 0.0839 -0.5176  8.2543
===========================================================================

Odds Ratio for electricity: 47.8612 (95% CI: 0.5959, 3843.9347)

============================================================
Dependent Variable: Air Barrier, Air Leakage, or Air Infiltration
  1's: 26, 0's: 28
                                       Results: Logit
============================================================================================
Model:              Logit                                         Pseudo R-squared: 0.060   
Dependent Variable: Air Barrier, Air Leakage, or Air Infiltration AIC:              74.2792 
Date:               2026-11-24 13:08                              BIC:              78.2572 
No. Observations:   54                                            Log-Likelihood:   -35.140 
Df Model:           1                                             LL-Null:          -37.393 
Df Residuals:       52                                            LLR p-value:      0.033764
Converged:          1.0000                                        Scale:            1.0000  
No. Iterations:     5.0000                                                                  
-----------------------------------------------------------------------------------------------
                                   Coef.     Std.Err.       z       P>|z|      [0.025    0.975]
-----------------------------------------------------------------------------------------------
const                             -0.9221      0.5020    -1.8368    0.0662    -1.9060    0.0618
Cost_of_Electricity_USD/KWH        4.6928      2.3368     2.0082    0.0446     0.1127    9.2729
============================================================================================

Odds Ratio for electricity: 109.1614 (95% CI: 1.1193, 10645.6891)

============================================================
SUMMARY FOR LAST THREE MECHANISMS
============================================================
                                    Mechanism    Coef  StdErr  p-value   Odds_Ratio   CI_low      CI_high  N_1  N_0
             Glazing Factors for Fenestration 14.8027  4.3741   0.0007 2683576.1577 507.5417 1.418914e+10   34   20
                            Permanent Shading  3.8683  2.2378   0.0839      47.8612   0.5959 3.843935e+03   22   32
Air Barrier, Air Leakage, or Air Infiltration  4.6928  2.3368   0.0446     109.1614   1.1193 1.064569e+04   26   28

Part 19: Final Individual Mechanism Results Table (Table 3)¶

This section extracts the regression results for the three key mechanisms and formats them into a standard journal table. It includes the coefficients, standard errors, constants, log-likelihood, and McFadden pseudo R² for each model, saving the output as Table_3.csv.

In [25]:
# ============================================================================
# Binary logistic regression for 3 selected mechanisms (Table 3)
# ============================================================================
from statsmodels.discrete.discrete_model import Logit
import statsmodels.api as sm
import pandas as pd
import numpy as np
import os

# Ensure output folder exists
current_dir = os.getcwd()
project_root = os.path.dirname(current_dir)
output_folder = os.path.join(project_root, 'Output')
os.makedirs(output_folder, exist_ok=True)

# Selected 3 mechanisms (note: column name must match df_enforcement_items exactly)
mechanisms_selected = [
    "Glazing Factors for Fenestration",
    "Thermal Transmittance or Insulation Calculations for Building Envelope",
    "Solar Heat Gains Calculations for Building Envelope"
]

# Display names for table columns
mechanisms_display_names = [
    "(1) Glazing factors",
    "(2) Thermal transmittance / insulation",
    "(3) Solar heat gain"
]

# Prepare data
X = df_enforcement_items[['Cost_of_Electricity_USD/KWH']]
X = sm.add_constant(X)

# Helper function for significance stars (Standard Economics convention)
def get_stars(p):
    if p < 0.01: return '***'
    elif p < 0.05: return '**'
    elif p < 0.10: return '*'
    else: return ''

# Dictionary to store results for each mechanism
table_data = {}

for i, mech in enumerate(mechanisms_selected):
    y = df_enforcement_items[mech]
    model = Logit(y, X)
    result = model.fit(disp=0)

    # Extract stats for electricity cost
    coef_elec = result.params['Cost_of_Electricity_USD/KWH']
    se_elec = result.bse['Cost_of_Electricity_USD/KWH']
    p_elec = result.pvalues['Cost_of_Electricity_USD/KWH']

    # Extract stats for constant
    coef_const = result.params['const']
    se_const = result.bse['const']
    p_const = result.pvalues['const']

    # Calculate model fit statistics
    llf = result.llf
    freq = y.value_counts(normalize=True)
    null_ll = np.sum(freq * np.log(freq)) * len(y)
    mcfadden_r2 = 1 - (llf / null_ll)

    # Get stars
    stars_elec = get_stars(p_elec)
    stars_const = get_stars(p_const)

    # Format strings
    elec_str = f"{coef_elec:.3f}{stars_elec}"
    elec_se_str = f"({se_elec:.3f})"
    const_str = f"{coef_const:.3f}{stars_const}"
    const_se_str = f"({se_const:.3f})"

    # Store in dictionary using the display name as column header
    # FIXED: changed [I] to [i]
    col_name = mechanisms_display_names[i]
    table_data[col_name] = [
        elec_str,
        elec_se_str,
        const_str,
        const_se_str,
        str(len(y)),
        f"{llf:.2f}",
        f"{mcfadden_r2:.3f}"
    ]

    # Print individual model summary for reference
    print(f"\n{'='*60}")
    print(f"Dependent Variable: {mech}")
    print(f"  1's: {y.sum()}, 0's: {len(y)-y.sum()}")
    print(result.summary2())

# Build the final Table 3 DataFrame
index_labels = [
    "Electricity cost (USD/kWh)",
    "",
    "Constant",
    "",
    "Observations",
    "Log-likelihood",
    "McFadden pseudo R²"
]

df_table3 = pd.DataFrame(table_data, index=index_labels)

# Print Table 3 to console
print("\n" + "="*80)
print("TABLE 3: BINARY LOGISTIC REGRESSION RESULTS")
print("="*80)
print(df_table3.to_string())

# Save Table 3
Table3_path = os.path.join(output_folder, 'Table_3.csv')
df_table3.to_csv(Table3_path)
print(f"\nTable 3 saved to: {Table3_path}")
============================================================
Dependent Variable: Glazing Factors for Fenestration
  1's: 34, 0's: 20
                                 Results: Logit
=================================================================================
Model:              Logit                            Pseudo R-squared: 0.289     
Dependent Variable: Glazing Factors for Fenestration AIC:              54.6256   
Date:               2026-11-24 13:08                 BIC:              58.6036   
No. Observations:   54                               Log-Likelihood:   -25.313   
Df Model:           1                                LL-Null:          -35.594   
Df Residuals:       52                               LLR p-value:      5.7705e-06
Converged:          1.0000                           Scale:            1.0000    
No. Iterations:     7.0000                                                       
----------------------------------------------------------------------------------
                               Coef.   Std.Err.     z     P>|z|    [0.025   0.975]
----------------------------------------------------------------------------------
const                         -1.6637    0.6425  -2.5894  0.0096  -2.9229  -0.4044
Cost_of_Electricity_USD/KWH   14.8027    4.3741   3.3842  0.0007   6.2296  23.3757
=================================================================================


============================================================
Dependent Variable: Thermal Transmittance or Insulation Calculations for Building Envelope
  1's: 42, 0's: 12
                                                    Results: Logit
======================================================================================================================
Model:              Logit                                                                  Pseudo R-squared: 0.174    
Dependent Variable: Thermal Transmittance or Insulation Calculations for Building Envelope AIC:              51.2662  
Date:               2026-11-24 13:08                                                       BIC:              55.2441  
No. Observations:   54                                                                     Log-Likelihood:   -23.633  
Df Model:           1                                                                      LL-Null:          -28.604  
Df Residuals:       52                                                                     LLR p-value:      0.0016154
Converged:          1.0000                                                                 Scale:            1.0000   
No. Iterations:     7.0000                                                                                            
------------------------------------------------------------------------------------------------------------------------------
                                        Coef.          Std.Err.            z            P>|z|           [0.025          0.975]
------------------------------------------------------------------------------------------------------------------------------
const                                  -0.3106           0.6019         -0.5161         0.6058         -1.4902          0.8690
Cost_of_Electricity_USD/KWH            11.3479           4.5701          2.4831         0.0130          2.3908         20.3051
======================================================================================================================


============================================================
Dependent Variable: Solar Heat Gains Calculations for Building Envelope
  1's: 32, 0's: 22
                                          Results: Logit
===================================================================================================
Model:              Logit                                               Pseudo R-squared: 0.140    
Dependent Variable: Solar Heat Gains Calculations for Building Envelope AIC:              66.7573  
Date:               2026-11-24 13:08                                    BIC:              70.7353  
No. Observations:   54                                                  Log-Likelihood:   -31.379  
Df Model:           1                                                   LL-Null:          -36.499  
Df Residuals:       52                                                  LLR p-value:      0.0013743
Converged:          1.0000                                              Scale:            1.0000   
No. Iterations:     6.0000                                                                         
-------------------------------------------------------------------------------------------------------
                                     Coef.      Std.Err.        z        P>|z|       [0.025      0.975]
-------------------------------------------------------------------------------------------------------
const                               -0.9855       0.5387     -1.8295     0.0673     -2.0413      0.0703
Cost_of_Electricity_USD/KWH          8.2395       2.9968      2.7494     0.0060      2.3659     14.1131
===================================================================================================


================================================================================
TABLE 3: BINARY LOGISTIC REGRESSION RESULTS
================================================================================
                           (1) Glazing factors (2) Thermal transmittance / insulation (3) Solar heat gain
Electricity cost (USD/kWh)           14.803***                               11.348**            8.239***
                                       (4.374)                                (4.570)             (2.997)
Constant                             -1.664***                                 -0.311             -0.986*
                                       (0.642)                                (0.602)             (0.539)
Observations                                54                                     54                  54
Log-likelihood                          -25.31                                 -23.63              -31.38
McFadden pseudo R²                       0.289                                  0.174               0.140

Table 3 saved to: your/path/to/reproducibility package/Output/Table_3.csv

Part 20: AME for Significant Mechanisms & Visualization (Table 4 & Figure 4)¶

This section calculates the Average Marginal Effects (AME) for the three statistically significant mechanisms in response to a $0.10 electricity price increase. It saves the summary statistics as Table_4_AME_Significant_Mechanisms.csv and generates a bar chart illustrating the probability changes, saved as Fig 4.png.

In [26]:
# Calculate and plot AME for three significant mechanisms
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.discrete.discrete_model import Logit
import statsmodels.api as sm
import os

# Ensure output folder exists
current_dir = os.getcwd()
project_root = os.path.dirname(current_dir)
output_folder = os.path.join(project_root, 'Output')
os.makedirs(output_folder, exist_ok=True)

# Define the three significant mechanisms (simplified names as in df_enforcement_items)
sig_mechanisms = [
    "Thermal Transmittance or Insulation Calculations for Building Envelope",
    "Solar Heat Gains Calculations for Building Envelope",
    "Glazing Factors for Fenestration"
]

# Prepare data
X_var = 'Cost_of_Electricity_USD/KWH'
X = df_enforcement_items[[X_var]]
X_const = sm.add_constant(X)

ame_results = []

for mech in sig_mechanisms:
    y = df_enforcement_items[mech]
    model = Logit(y, X_const)
    result = model.fit(disp=0)
    
    # Baseline predicted probabilities
    prob_base = result.predict(X_const)
    # Increase electricity by $0.10
    X_new = X_const.copy()
    X_new[X_var] = X_new[X_var] + 0.10
    prob_new = result.predict(X_new)
    # Average marginal effect in percentage points
    ame_pct = (prob_new - prob_base).mean() * 100
    baseline_pct = prob_base.mean() * 100
    
    ame_results.append({
        'Mechanism': mech,
        'Baseline_Prob_%': baseline_pct,
        'AME_%': ame_pct
    })
    
    print(f"\n{mech}")
    print(f"  Baseline probability: {baseline_pct:.2f}%")
    print(f"  After +$0.10: change = {ame_pct:+.2f} percentage points")

# Create summary DataFrame
df_ame = pd.DataFrame(ame_results)
print("\nSummary of AME for significant mechanisms:")
print(df_ame.round(2).to_string(index=False))

# ============================================================
# SAVE TABLE 4: AME Summary for Significant Mechanisms
# ============================================================

print("\n" + "="*60)
print("SAVING TABLE 4: AME FOR SIGNIFICANT MECHANISMS")
print("="*60)

df_ame.to_csv(os.path.join(output_folder, 'Table_4_AME_Significant_Mechanisms.csv'),
              index=False, float_format='%.2f')

print(f"Table 4 saved to: {os.path.join(output_folder, 'Table_4_AME_Significant_Mechanisms.csv')}")
print("  - Contains: Mechanism, Baseline_Prob_%, AME_%")

# ============================================================
# PLOT AND SAVE FIGURE 4: AME Bar Chart
# ============================================================

# Plot
fig, ax = plt.subplots(figsize=(8, 5))
mechanisms_short = ['Thermal\nTransmittance', 'Solar Heat\nGains', 'Glazing\nFactors']
ame_vals = df_ame['AME_%'].values
colors = ['#2c7bb6', '#fdae61', '#d7191c']
bars = ax.bar(mechanisms_short, ame_vals, color=colors, alpha=0.7)
ax.axhline(0, color='black', linewidth=0.8)
ax.set_ylabel('Average Marginal Effect (percentage points)')
ax.set_title('AME of $0.10 Electricity Price Increase on Probability of Enforcement')
ax.grid(axis='y', linestyle='--', alpha=0.5)

for bar, val in zip(bars, ame_vals):
    ax.text(bar.get_x() + bar.get_width()/2., 
            val + (0.5 if val >= 0 else -1.5),
            f'{val:.2f}%', ha='center', va='bottom' if val >= 0 else 'top', fontsize=10)

plt.tight_layout()

# Save Figure 4
plt.savefig(os.path.join(output_folder, 'Fig 4.png'), dpi=300, bbox_inches='tight')
print(f"Figure 21 saved to: {os.path.join(output_folder, 'Fig 4.png')}")

plt.show()
Thermal Transmittance or Insulation Calculations for Building Envelope
  Baseline probability: 77.78%
  After +$0.10: change = +12.69 percentage points

Solar Heat Gains Calculations for Building Envelope
  Baseline probability: 59.26%
  After +$0.10: change = +15.32 percentage points

Glazing Factors for Fenestration
  Baseline probability: 62.96%
  After +$0.10: change = +20.65 percentage points

Summary of AME for significant mechanisms:
                                                             Mechanism  Baseline_Prob_%  AME_%
Thermal Transmittance or Insulation Calculations for Building Envelope            77.78  12.69
                   Solar Heat Gains Calculations for Building Envelope            59.26  15.32
                                      Glazing Factors for Fenestration            62.96  20.65

============================================================
SAVING TABLE 4: AME FOR SIGNIFICANT MECHANISMS
============================================================
Table 4 saved to: your/path/to/reproducibility package/Output/Table_4_AME_Significant_Mechanisms.csv
  - Contains: Mechanism, Baseline_Prob_%, AME_%
Figure 21 saved to: your/path/to/reproducibility package/Output/Fig 4.png
No description has been provided for this image

Part 21: Appendix C - Descriptive Evidence on Electricity Price Tiers and U-value Standards¶

This section replicates the supplementary descriptive evidence in Appendix C. It groups the 54 countries into three electricity price tiers (Low, Medium, High) based on their 2023 electricity costs, calculates the adoption rate of thermal transmittance (U-value) standards within each tier, and compares the mean electricity prices between countries with and without the standard.

In [27]:
# ============================================================================
# Part 21: Appendix C - Descriptive Evidence on Electricity Price Tiers and U-value Standards
# ============================================================================
import pandas as pd
import numpy as np
import os

# Ensure output folder exists
current_dir = os.getcwd()
project_root = os.path.dirname(current_dir)
output_folder = os.path.join(project_root, 'Output')
os.makedirs(output_folder, exist_ok=True)

print("\n" + "="*80)
print("APPENDIX C: DESCRIPTIVE EVIDENCE ON PRICE TIERS AND U-VALUE STANDARDS")
print("="*80)

# We use df_enforcement_items because it already has the binary outcome 
df_appC = df_enforcement_items.copy()

# Define the tiers based on the paper's thresholds
def get_price_tier(price):
    if price < 0.10:
        return "Low (< $0.10)"
    elif 0.10 <= price <= 0.20:
        return "Medium ($0.10 - $0.20)"
    else:
        return "High (> $0.20)"

df_appC['Price_Tier'] = df_appC['Cost_of_Electricity_USD/KWH'].apply(get_price_tier)

# 1. Calculate adoption rates by tier
print("\n--- Adoption Rates by Electricity Price Tier ---")
tier_stats = df_appC.groupby('Price_Tier').agg(
    Mean_Price=('Cost_of_Electricity_USD/KWH', 'mean'),
    Adoption_Rate=('Thermal Transmittance or Insulation Calculations for Building Envelope', 'mean'),
    Count=('Cost_of_Electricity_USD/KWH', 'count')
)
tier_stats['Adoption_Rate_%'] = tier_stats['Adoption_Rate'] * 100

tier_order = ["Low (< $0.10)", "Medium ($0.10 - $0.20)", "High (> $0.20)"]
final_tier_stats = tier_stats.loc[tier_order, ['Mean_Price', 'Adoption_Rate_%', 'Count']]
print(final_tier_stats.round(3).to_string())

# 2. Calculate mean price for adopters vs non-adopters
print("\n--- Mean Electricity Price: Adopters vs Non-Adopters ---")
mean_price_no_std = df_appC[df_appC['Thermal Transmittance or Insulation Calculations for Building Envelope'] == 0]['Cost_of_Electricity_USD/KWH'].mean()
mean_price_with_std = df_appC[df_appC['Thermal Transmittance or Insulation Calculations for Building Envelope'] == 1]['Cost_of_Electricity_USD/KWH'].mean()

print(f"Mean price for countries WITHOUT U-value standard: ${mean_price_no_std:.3f}/kWh")
print(f"Mean price for countries WITH U-value standard:    ${mean_price_with_std:.3f}/kWh")
print(f"Ratio (Without / With): {mean_price_no_std / mean_price_with_std:.2f}")

# ============================================================================
# Save to CSV
# ============================================================================
tier_export_path = os.path.join(output_folder, 'Table_Appendix_C_Tiers.csv')
final_tier_stats.to_csv(tier_export_path)
print(f"\nAppendix C Tier Stats saved to: {tier_export_path}")

means_df = pd.DataFrame({
    'Group': ['Without U-value Standard', 'With U-value Standard'],
    'Mean_Price': [mean_price_no_std, mean_price_with_std]
})
means_export_path = os.path.join(output_folder, 'Table_Appendix_C_Means.csv')
means_df.to_csv(means_export_path, index=False, float_format='%.3f')
print(f"Appendix C Means saved to: {means_export_path}")
================================================================================
APPENDIX C: DESCRIPTIVE EVIDENCE ON PRICE TIERS AND U-VALUE STANDARDS
================================================================================

--- Adoption Rates by Electricity Price Tier ---
                        Mean_Price  Adoption_Rate_%  Count
Price_Tier                                                
Low (< $0.10)                0.049           58.824     17
Medium ($0.10 - $0.20)       0.145           75.000     16
High (> $0.20)               0.318           95.238     21

--- Mean Electricity Price: Adopters vs Non-Adopters ---
Mean price for countries WITHOUT U-value standard: $0.091/kWh
Mean price for countries WITH U-value standard:    $0.208/kWh
Ratio (Without / With): 0.44

Appendix C Tier Stats saved to: your/path/to/reproducibility package/Output/Table_Appendix_C_Tiers.csv
Appendix C Means saved to: your/path/to/reproducibility package/Output/Table_Appendix_C_Means.csv

Part 22: Data Integrity Verification (SHA256 Hashes)¶

This section calculates the SHA256 hashes for all raw data files in the Data folder. It prints the hashes in a Markdown table format, which can be directly copied into the README to verify data integrity. We also addressed unpublic data here

In [28]:
# Addressing non-Public Data
current_dir = os.getcwd()
project_root = os.path.dirname(current_dir)
data_folder = os.path.join(project_root, 'Data')
output_folder = os.path.join(project_root, 'Output')

print("Cleaning raw WPR CSV...")
file_path_raw = os.path.join(data_folder, 'Input-Cost of Electricity by Country.csv')
df_raw = pd.read_csv(file_path_raw)
cols_to_blank = ['2023', '2024', '2025']
for col in cols_to_blank:
    if col in df_raw.columns:
        df_raw[col] = pd.NA 
df_raw.to_csv(file_path_raw, index=False)
print("Raw file cleaned.")

print("Cleaning Output CSVs...")

output_files = ['Merged_All_Countries_Final.csv', 'Final_54_Countries.csv']
for filename in output_files:
    file_path = os.path.join(output_folder, filename)
    if os.path.exists(file_path):
        df_out = pd.read_csv(file_path)
        col_name = 'Cost_of_Electricity_2023_USD/KWH' 
        if col_name in df_out.columns:
            df_out[col_name] = pd.NA 
            df_out.to_csv(file_path, index=False)
            print(f"{filename} cleaned.")
print("All restricted data has been blanked.")
Cleaning raw WPR CSV...
Raw file cleaned.
Cleaning Output CSVs...
Merged_All_Countries_Final.csv cleaned.
Final_54_Countries.csv cleaned.
All restricted data has been blanked.
In [29]:
import hashlib
import os
import pandas as pd

# ============================================================================
# Calculate SHA256 Hashes for ALL files in the Data folder
# ============================================================================

# Set up paths
current_dir = os.getcwd()
project_root = os.path.dirname(current_dir)
data_folder = os.path.join(project_root, 'Data')
output_folder = os.path.join(project_root, 'Output') 
os.makedirs(output_folder, exist_ok=True)

def get_sha256(file_path):
    """Calculate SHA256 hash of a file."""
    sha256_hash = hashlib.sha256()
    with open(file_path, "rb") as f:
        # Read in chunks to handle large files efficiently
        for byte_block in iter(lambda: f.read(4096), b""):
            sha256_hash.update(byte_block)
    return sha256_hash.hexdigest()

print("="*80)
print("SHA256 HASHES FOR ALL DATA FILES")
print("="*80)

# Loop through all files in the Data folder
hash_results = []
if os.path.exists(data_folder):
    for filename in sorted(os.listdir(data_folder)):
        # Skip hidden files (like .DS_Store) and directories
        if filename.startswith('.') or not os.path.isfile(os.path.join(data_folder, filename)):
            continue
            
        file_path = os.path.join(data_folder, filename)
        hash_val = get_sha256(file_path)
        hash_results.append((filename, hash_val))
        
        print(f"File: {filename}")
        print(f"SHA256: {hash_val}\n")
else:
    print(f"⚠️ Data folder not found at: {data_folder}")

# ============================================================================
# Print in Markdown format for easy copy-pasting into README
# ============================================================================
print("="*80)
print("MARKDOWN FORMAT (Copy and paste into README.md):")
print("="*80)
print("| File | SHA256 |")
print("|:---|:---|")
for filename, hash_val in hash_results:
    print(f"| `{filename}` | `{hash_val}` |")
print("="*80)

# ============================================================================
# NEW: Save to data_hash_report.csv in Output folder
# ============================================================================
df_hashes = pd.DataFrame(hash_results, columns=['File', 'SHA256'])
hash_report_path = os.path.join(output_folder, 'data_hash_report.csv')
df_hashes.to_csv(hash_report_path, index=False)
print(f"\n✅ Data hash report saved to: {hash_report_path}")
================================================================================
SHA256 HASHES FOR ALL DATA FILES
================================================================================
File: Input-Building-green-dataset-final-05-13-2024.xlsx
SHA256: cc05918878c5abec454c39fc8ba0dad10154dc4bd343cd7a645a009e8ec2edc5

File: Input-Corruption_Perceptions_Index 2023.csv
SHA256: b4bc10b1ca570ba3de136c9fa09410869c5672341f45a15a129961a6138cc2e4

File: Input-Cost of Electricity by Country.csv
SHA256: 53d519deb5fe0f57e3549673dfb30f85e0f205eb01d1ba883ba1b9e30cf73355

File: Input-Cost of Electricity by Country_original.csv
SHA256: 936c69c8faf303ab6f790aec9cbd9d798d50cfc82b0133b33df0e33bc90347f2

File: Input-GDP_Per_Capita_Data.csv
SHA256: 3fafd8e60f50fbd0fc31c63b6716bc5293a479b50e425580941389e3a2ad173b

File: Input-Global_Adaption_2023.csv
SHA256: df4057b65aeefd4c8741ee7c6897e397d845f9b7bc815964117e9fb5003504d1

File: Input-Government_Effectiveness.csv
SHA256: 796f9a86b517d7501fa1e7a417cb356f6a51459ba51670b4dd4ba7365065dea1

File: Input-Urban_Population_Rate_Data.csv
SHA256: 95c50136a2a620ba04cfa8242a1eb192bb363f76f1fdfac350f3b1f45d211fe3

================================================================================
MARKDOWN FORMAT (Copy and paste into README.md):
================================================================================
| File | SHA256 |
|:---|:---|
| `Input-Building-green-dataset-final-05-13-2024.xlsx` | `cc05918878c5abec454c39fc8ba0dad10154dc4bd343cd7a645a009e8ec2edc5` |
| `Input-Corruption_Perceptions_Index 2023.csv` | `b4bc10b1ca570ba3de136c9fa09410869c5672341f45a15a129961a6138cc2e4` |
| `Input-Cost of Electricity by Country.csv` | `53d519deb5fe0f57e3549673dfb30f85e0f205eb01d1ba883ba1b9e30cf73355` |
| `Input-Cost of Electricity by Country_original.csv` | `936c69c8faf303ab6f790aec9cbd9d798d50cfc82b0133b33df0e33bc90347f2` |
| `Input-GDP_Per_Capita_Data.csv` | `3fafd8e60f50fbd0fc31c63b6716bc5293a479b50e425580941389e3a2ad173b` |
| `Input-Global_Adaption_2023.csv` | `df4057b65aeefd4c8741ee7c6897e397d845f9b7bc815964117e9fb5003504d1` |
| `Input-Government_Effectiveness.csv` | `796f9a86b517d7501fa1e7a417cb356f6a51459ba51670b4dd4ba7365065dea1` |
| `Input-Urban_Population_Rate_Data.csv` | `95c50136a2a620ba04cfa8242a1eb192bb363f76f1fdfac350f3b1f45d211fe3` |
================================================================================

✅ Data hash report saved to: your/path/to/reproducibility package/Output/data_hash_report.csv
In [ ]: